首页 > 解决方案 > 涉及 MutableSharedFlow 的测试 - java.lang.IllegalStateException:此作业尚未完成

问题描述

为这可能是一个非常业余的问题道歉。我正在掌握流程并在相关的测试MutableSharedFlow方面遇到问题。

以下是我可以构建的重现问题的最简单示例:

@ExperimentalCoroutinesApi
@ExperimentalTime
class MyExampleTest {

    val testDispatcher: TestCoroutineDispatcher = TestCoroutineDispatcher()

    @Test
    fun test() = testDispatcher.runBlockingTest  {
        val sharedFlow = MutableSharedFlow<String>()

        sharedFlow.take(2).collect {
            println(it)
        }

        sharedFlow.tryEmit("Hello")
        sharedFlow.tryEmit("World")
    }
}

这导致他出现以下错误:

java.lang.IllegalStateException: This job has not completed yet

    at kotlinx.coroutines.JobSupport.getCompletionExceptionOrNull(JobSupport.kt:1187)
    at kotlinx.coroutines.test.TestBuildersKt.runBlockingTest(TestBuilders.kt:53)
    at kotlinx.coroutines.test.TestBuildersKt.runBlockingTest(TestBuilders.kt:80)
    at com.example.MyExampleTest.test(MyExampleTest.kt:22)

根据我有限的理解,我认为这与SharedFlow永远不会完成的事实有关。但我认为拥有take(2)会减轻这种情况。任何建议,将不胜感激!

标签: androidkotlinkotlin-coroutineskotlin-android-extensionskotlin-flow

解决方案


根据我有限的理解,我认为这与 SharedFlow 从未完成的事实有关。

你是对的,这或多或少是个问题。Flow 是基于 Coroutines 的,协程还没有完成。

在我看来,对流进行单元测试的最佳方法是 Turbine:

https://github.com/cashapp/turbine

// Cold Flow
flowOf("one", "two").test {
  assertEquals("one", expectItem())
  assertEquals("two", expectItem())
  expectComplete()
}

// Hot Flow
MutableStateFlow("test").test {
    assertThat(expectItem()).isEqualTo("test")
    cancelAndConsumeRemainingEvents()
}

关于这个确切的“问题”还有一个未解决的问题:

https://github.com/Kotlin/kotlinx.coroutines/issues/1204


推荐阅读