How to unit test coruotine with livedata

383 views Asked by At

On the way of learning unit test with mockK I came across with this scenario:

MyViewModel:

private val _spinner: MutableLiveData<Boolean> = MutableLiveData()

val getSpinner : LiveData<Boolean>
get() = _spinner

fun launchCoruotine() {
    viewModelScope.launch {
        repository.refreshTitle()
        _spinner.value = true
    }
} 

dummy repository:

suspend fun refreshTitle() {
    delay(4000)
}

How do I write unit test for _spinner whether its value changed after refreshTitle returns

Thanks in advance!

1

There are 1 answers

1
Saurabh Thorat On

You can use this test which verifies that the spinner LiveData value has changed to true after invoking launchCoroutine():

@Test
fun spinnerTest() = runBlockingTest {
    val observer = mockk<Observer<Boolean>>()
    viewModel.getSpinner.observeForever(observer)

    viewModel.launchCoroutine()

    verify { observer.onChanged(true) }
}