涉及 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) 可以缓解这种情况。任何建议将不胜感激!

解决方法

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

你说得对,这或多或少是问题所在。 Flow基于Coroutines,协程未完成。

在我看来,对 Flows 进行单元测试的最佳方法是 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