[英]How to unit test coruotine with livedata
On the way of learning unit test with mockK I came across with this scenario:在使用 mockK 学习单元测试的过程中,我遇到了这种情况:
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如何为 _spinner 编写单元测试,它的值在 refreshTitle 返回后是否发生了变化
Thanks in advance!提前致谢!
You can use this test which verifies that the spinner LiveData value has changed to true after invoking launchCoroutine()
:您可以使用此测试来验证在调用
launchCoroutine()
后微调器 LiveData 值是否已更改为 true:
@Test
fun spinnerTest() = runBlockingTest {
val observer = mockk<Observer<Boolean>>()
viewModel.getSpinner.observeForever(observer)
viewModel.launchCoroutine()
verify { observer.onChanged(true) }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.