gpt4 book ai didi

android - 涉及 MutableSharedFlow 的测试 - java.lang.IllegalStateException : This job has not completed yet

转载 作者:行者123 更新时间:2023-12-04 03:40:16 25 4
gpt4 key购买 nike

很抱歉这可能是一个非常业余的问题。我开始掌握流程,并在涉及 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) 可以缓解这种情况。如有任何建议,我们将不胜感激!

最佳答案

From my limited understanding I think it's something to do with the fact that SharedFlow never completes.

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

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

关于android - 涉及 MutableSharedFlow 的测试 - java.lang.IllegalStateException : This job has not completed yet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66186024/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com