【发布时间】:2020-02-06 15:19:41
【问题描述】:
我正在编写单元测试,当我在执行挂起函数之前和之后更改可观察值时,我遇到了这种特殊情况。我想编写一个单元测试来检查值是否正确更改了两次。
方法如下:
fun doSomething() {
viewModelScope.launch(ioDispatcher) {
try {
viewModelScope.launch(Dispatchers.Main) {
commandLiveData.value = Pair(CANCEL_TIMER, null)
}
isProgress.set(true) //need to test it was set to true in one test
checkoutInteractor.doSomethingElse().run {
handleResult(this)
}
isProgress.set(false) //need to test it was set to false here in another test
} catch (ex: java.lang.Exception) {
handleHttpError(ex)
isProgress.set(false)
}
}
}
在编写测试时,我调用了doSomething(),但我不确定如何检测到该值在调用checkoutInteractor.doSomethingElse 之前设置为true,之后设置为false。
这是我的测试
@Test
fun `test doSomething enables progress`() {
runBlockingTest {
doReturn(Response()).`when`(checkoutInteractor). checkoutInteractor.doSomethingElse()
viewModel.doSomething()
assertTrue(viewModel.isProgress.get()) //fails obviously as the value was already set to false after the `doSomethingElse` was executed.
}
}
顺便说一句,isProgress 是 ObservableBoolean
【问题讨论】:
标签: android unit-testing kotlin kotlin-coroutines