gpt4 book ai didi

kotlin-coroutines - 如何对MutableSharedFlow (replay = 0)发出值进行单元测试?

转载 作者:行者123 更新时间:2023-12-03 17:20:00 25 4
gpt4 key购买 nike

我无法弄清楚如何测试带有SharedFlowreplay=0发出的值。

import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.runBlocking
import org.junit.Test

class ShowcaseTest {

@Test
fun testIntSharedFlowFlow() {
val intSharedFlow = MutableSharedFlow<Int>()

runBlocking {
intSharedFlow.emit(1)
}

// Does not work as there is no buffer because MutableSharedFlow(replay=0)
assert(intSharedFlow.replayCache.first() == 1)
}
}

最佳答案

您可以改用tryEmit()并验证返回的结果
更新:
考虑使用Turbine
例如:

sharedFlow.test {
sharedFlow.emit(1)
assertEquals(expected = 1, expectItem())
cancelAndIgnoreRemainingEvents()

}

关于kotlin-coroutines - 如何对MutableSharedFlow <T>(replay = 0)发出值进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65235632/

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