Search code examples
androidandroid-livedataandroid-architecture-componentskotest

Using LiveDataTestUtil with Kotest


I have been reading through the LiveDatatestUtil.kt provided as part of the Android Architecture Components Samples, and I have been trying to work out how to test Events with it within Kotest, so far as possible. Mainly because (right now) Kotest doesn't provide LiveData testing capability. Is there an idiomatic way to test Events (based on LiveData), that is based on the published util?


Solution

  • My solution is add the following to the util:

    @VisibleForTesting(otherwise = VisibleForTesting.NONE)
    infix fun <T, U : T> LiveData<Event<T>>.shouldBeTriggered(
        expected: U
    ) {
        val value = this.getOrAwaitValue()
        value.getContentIfNotHandled() shouldBe expected
    }
    

    This then allows use of event shouldBeTriggered withValue as a test.