Android:使用kotlin协同程序无法正常工作的ViewModel测试

问题描述 投票:0回答:1

我第一次使用协同程序而且我在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()
    ...
}

我不嘲笑某事或不做某事吗?提前致谢!

android kotlin kotlinx.coroutines android-viewmodel
1个回答
1
投票

TestCoroutineContext调度程序可用于处理测试中的计时,但您希望同步运行异步调用。您应该能够使用Unconfined调度程序实现此目的。

© www.soinside.com 2019 - 2024. All rights reserved.