使用 shareIn() 测试 Kotlin 流程

nha*_*man 5 turbine kotlin kotlin-coroutines

我正在尝试测试shareIn与 Turbine 一起使用的 Flow,但我有点迷失为什么我的测试失败以及如何修复它。

class MyTest {

    private val scope = CoroutineScope(Dispatchers.Default)
    private val mutableSharedFlow = MutableSharedFlow<Int>()

    @Test
    fun succeeds() = runBlocking {
        val sharedFlow = mutableSharedFlow

        sharedFlow.test {
            expectNoEvents()
            mutableSharedFlow.emit(3)
            expect(expectItem()).toBe(3)
        }
    }

    @Test
    fun fails() = runBlocking {
        val sharedFlow = mutableSharedFlow
            .shareIn(scope, started = SharingStarted.WhileSubscribed())

        sharedFlow.test {
            expectNoEvents()
            mutableSharedFlow.emit(3)
            expect(expectItem()).toBe(3)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在这些测试中,第一个succeeds()测试运行良好,但是一旦我将其包含shareInfails()测试中,测试就会失败并超时:

Timed out waiting for 1000 ms
kotlinx.coroutines.TimeoutCancellationException: Timed out waiting for 1000 ms
    (Coroutine boundary)
    at app.cash.turbine.ChannelBasedFlowTurbine$expectEvent$2.invokeSuspend(FlowTurbine.kt:238)
    at app.cash.turbine.ChannelBasedFlowTurbine$withTimeout$2.invokeSuspend(FlowTurbine.kt:206)
    at app.cash.turbine.ChannelBasedFlowTurbine.expectItem(FlowTurbine.kt:243)
Run Code Online (Sandbox Code Playgroud)

我应该做什么来测试使用的流程shareIn

Ana*_*lii 8

我不知道你为什么决定使用范围,Dispatchers.Default如下所示:

...
private val scope = CoroutineScope(Dispatchers.Default)
...
Run Code Online (Sandbox Code Playgroud)

对于测试,只需使用Dispatchers.Unconfined代替,因为它会立即在当前线程上执行协程,而这正是您所需要的。

...
private val scope = CoroutineScope(Dispatchers.Unconfined)
...
Run Code Online (Sandbox Code Playgroud)

因此,应用上述更改后,您的两个测试都成功通过。

您可以在这里找到我针对此问题的示例项目。