相关疑难解决方法(0)

使用 shareIn() 测试 Kotlin 流程

我正在尝试测试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) …
Run Code Online (Sandbox Code Playgroud)

turbine kotlin kotlin-coroutines

5
推荐指数
1
解决办法
3504
查看次数

标签 统计

kotlin ×1

kotlin-coroutines ×1

turbine ×1