【发布时间】:2021-02-02 22:05:18
【问题描述】:
以下测试未通过。永远不会打印字符串“在添加 XXX 之前”。
@Test
fun testFoo() = runBlocking {
val testCoroutineScope = TestCoroutineScope().apply {
pauseDispatcher() // This needs to be here because the actual test handles time.
}
val sharedFlow = MutableSharedFlow<Int>()
val values = mutableListOf<Int>()
println("before launch")
val job = testCoroutineScope.launch {
println("before collect")
sharedFlow.collect {
println("before adding $it")
values.add(it)
}
}
println("before emits")
sharedFlow.emit(1)
sharedFlow.emit(2)
testCoroutineScope.runCurrent()
assertEquals(mutableListOf(1, 2), values)
job.cancel()
}
一旦收集部分被处理,我想有一种方法来emit 值。我不能设置replay 值,也不能使用onSubscription,因为这会改变业务逻辑。
添加 delay 或 yield 似乎没有任何区别,因此可能不是比赛条件。
如果pauseDispatcher() 被评论,则测试通过。
我的理解是,emit 将暂停,直到调用 collect lambda。
【问题讨论】:
标签: unit-testing kotlin-coroutines