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!
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) }
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.