android / codelab-kotlin-coroutines

Kotlin Coroutines codelab
Apache License 2.0
552 stars 268 forks source link

Use `LiveData<T>.value` in unit test on Kotlin Coroutines 6. Testing coroutines through behavior #69

Open arctouch-ianribas opened 4 years ago

arctouch-ianribas commented 4 years ago

Wouldn't it be simpler to just use LiveData<T>.value in the com.example.android.kotlincoroutines.main.MainViewModelTest#whenMainClicked_updatesTaps unit test?

getValueForTest() seems a convoluted way to get to the same place. I understand it might be different in some circumstances, but not in this test.

I implemented it like so:

    @Test
    fun whenMainClicked_updatesTaps() {
        subject.onMainViewClicked()
        assertThat(subject.taps.value).isEqualTo("0 taps")
        coroutineScope.advanceTimeBy(1_000)
        assertThat(subject.taps.value).isEqualTo("1 taps")
    }

I also prefer to statically import assertThat so the test is less polluted, but that is a matter of taste, of course. And it is true that the presence of the Truth class there, was important for me to know where the method was coming from.