android - 涉及 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 的,协程还没有完成。
在我看来,对流进行单元测试的最佳方法是 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()
}
关于这个确切的“问题”还有一个未解决的问题:
推荐阅读
- linux - 脚本不会自动从 root 切换到普通用户
- python - This issue about keras model and how to compile the model
- twitter-bootstrap - CSS Bootstrap 两列布局
- php - 如何解决 XAMPP 中的禁止访问问题
- c# - C# 事件订阅者排队
- pandas - 如何将 Keras 输入的形状纠正为 3D 数组
- c - 为什么 FREAD 在 Linux 上给出错误,但在 Windows 上却没有?
- android - 可扩展的 Recyclerview Android
- python-3.x - 电报错误 401:通过电报 cli 注册后的 USER_DEACTIVATED
- c - “make clean”的任务配置在 Visual Studio 2017 中不起作用