【问题标题】:Getting kotlin error "After waiting for 60000 ms, the test coroutine is not completing"获取 kotlin 错误“等待 60000 毫秒后,测试协程未完成”
【发布时间】:2022-07-13 23:28:10
【问题描述】:

我是测试新手,试图获取第二个流值并断言它,当我一个接一个地运行这个测试时运行良好,但是当我运行整个测试时,一旦第一个测试运行良好,其余的测试给我超时错误。

错误:

After waiting for 60000 ms, the test coroutine is not completing
kotlinx.coroutines.test.UncompletedCoroutinesError: After waiting for 60000 ms, the test coroutine is not completing
    at app//kotlinx.coroutines.test.TestBuildersKt__TestBuildersKt$runTestCoroutine$3$3.invokeSuspend(TestBuilders.kt:304)
    (Coroutine boundary)
@OptIn(ExperimentalCoroutinesApi::class)
class HomeViewModelTest {

    private lateinit var viewModel: HomeViewModel
    private val testDispatcher = UnconfinedTestDispatcher()

    @Before
    fun setup() {
        viewModel = HomeViewModel(FakeOrderRepository())
        Dispatchers.setMain(testDispatcher)
    }

    @After
    fun tearDown() {
        Dispatchers.resetMain()
        testDispatcher.cancel()
    }

    @Test
    fun flowViewModelTesting1() = runTest {
        val result = viewModel.homeUiState.drop(1).first()
        assertThat(true).isTrue()
    }


    @Test
    fun flowViewModelTesting2() = runTest {
        val result = viewModel.homeUiState.drop(1).first()
        assertThat(true).isTrue()
    }
}

【问题讨论】:

  • 如何更新homeUiState 的值?确定更新了吗?
  • 看起来homeUiState 在每个测试会话中始终只更新一次,因此只有第一个测试完成。您是否在 HomeViewModel 的实例之间共享一些状态/对象,这可能导致 homeUiState 仅更新一次,即使创建了多个 HomeViewModel 实例也是如此?

标签: android kotlin kotlin-coroutines kotlin-flow


【解决方案1】:

当您使用 runTest 时,默认情况下您使用的是 StandardTestDispatcher,这意味着它不会立即运行。 您必须从用于 ViewModel 的同一调度程序启动测试

替换

runTest {

testDispather.runTest {

它应该工作,试一试。如果不检查您的视图模型代码,我无法分享太多内容。

【讨论】:

    猜你喜欢
    • 2023-01-28
    • 1970-01-01
    • 1970-01-01
    • 2019-11-01
    • 2021-10-27
    • 2014-05-10
    • 2019-06-19
    • 2017-08-31
    • 1970-01-01
    相关资源
    最近更新 更多