我第一次使用协程,在测试我的工作时遇到问题
ViewModel
.
测试失败
Wanted but not invoked:
observer.onChanged(<Capturing argument>);
val androidVersioningMock: Versioning.AndroidVersioning = mock {
on { required } doAnswer { "3.3.6" }
}
val versioningMock: Versioning = mock {
on { android } doAnswer { androidVersioningMock }
}
whenever(networkManager.getAppVersionAsync()).thenReturn(GlobalScope.async { versioningMock })
runBlocking {
updateVersionModel =
UpdateViewModel(application, coroutineDispatcherProvider).apply {
updateLiveData.observeForever(stateObserver)
}
verify(stateObserver).onChanged(stateCaptor.capture())
assertTrue(stateCaptor.lastValue is UpdateState.NoUpdate)
assertEquals(UpdateState.NoUpdate, stateCaptor.lastValue)
}
我嘲笑了
coroutineDispatcherProvider
@ExperimentalCoroutinesApi
override val coroutineDispatcherProvider = mock<CoroutineDispatcherProvider> {
on { main } doAnswer { TestCoroutineContext() }
on { io } doAnswer { TestCoroutineContext() }
}
在我的ViewModel中,失败的方法是
private suspend fun getUpdateVersion(): Versioning =
withContext(coroutineDispatcherProvider.io) {
networkManager.getAppVersionAsync().await()
}
launch {
val versioningModel = getUpdateVersion()
...
}
我不是在嘲笑什么还是不做什么?提前谢谢!