我正在编写单元测试,当我在执行暂停功能之前然后之后更改可观察值时,就遇到了这种特殊情况。我想编写一个单元测试,以检查该值是否正确更改了两次。
方法如下:
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
最佳答案
您需要模拟或监视isProgress
和checkoutInteractor
字段,以记录和验证其方法的执行。
isProcess
和checkoutInteractor
的模拟或 spy 传递到您的类(class)中。 doSomething()
set()
和doSomethingElse()
函数例:
@Test
fun `test doSomething enables progress`() {
runBlockingTest {
val checkoutInteractor = Mockito.spy(CheckoutInteractor())
val isProcess = Mockito.spy(ObservableBoolean(true))
val viewModel = ViewModel(isProcess, checkoutInteractor)
viewModel.doSomething()
val inOrder = inOrder(isProcess, checkoutInteractor)
inOrder.verify(isProcess).set(true)
inOrder.verify(checkoutInteractor).doSomethingElse()
inOrder.verify(isProcess).set(false)
}
}
关于android - 测试协程中可观察到的场变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60098269/