SuperAPI AI 工具集

testing-flows-with-turbine

测试与质量

查看项目

更新于 10-16 04:36

技能介绍

用途

Testing Flows With Turbine 解决的是 Kotlin 协程 Flow 测试中的断言问题:当被测类暴露 StateFlow、SharedFlow 等流时,如何在测试中逐个断言每一次发射,而不是让测试挂起。Turbine 被称为逐个断言 Flow 发射值的标准方式,内置取消机制可防止 StateFlow、SharedFlow 等热流导致测试挂起。

主要能力

该技能覆盖以下内容:

  • flow.test 入口与 ReceiveTurbine API。
  • turbineScope 用于多流测试。
  • 独立 Turbine<T>,用于捕获回调与一次性信号。
  • 说明在什么情况下原始的 flow.toList() 反而优于 Turbine。

flow.test 的签名:

public suspend fun <T> Flow<T>.test(
    timeout: Duration = 3.seconds,
    name: String? = null,
    validate: suspend ReceiveTurbine<T>.() -> Unit,
)

ReceiveTurbine 提供挂起方法(awaitItem、awaitComplete、awaitError、awaitEvent、skipItems、cancel、cancelAndIgnoreRemainingEvents、cancelAndConsumeRemainingEvents)与非挂起方法(expectNoEvents、expectMostRecentItem、ensureAllEventsConsumed),以及同步消费的 takeItem / takeComplete / takeError。

使用方式

依赖安装(仅限测试依赖):

testImplementation("app.cash.turbine:turbine:1.x")

外围测试必须是 runTest { … } 体或任意挂起上下文,flow.test { } 本身即为挂起函数。多流测试需使用 @OptIn(ExperimentalCoroutinesApi::class),因为 turbineScope 与 TestScope.backgroundScope 交互。

多流交织断言可使用 turbineScope 与 testIn:

runTest(mainRule.dispatcher) {
    turbineScope {
        val items = repo.items.testIn(backgroundScope, name = "items")
        val errors = repo.errors.testIn(backgroundScope, name = "errors")
        assertEquals(0, items.awaitItem())
        assertEquals(emptyList<Throwable>(), errors.expectMostRecentItem())
        items.cancel()
        errors.cancel()
    }
}

独立 Turbine<T> 可用于非 Flow 场景(回调、监听器接口、自建 Channel、需要记录调用的 fake):

@Test fun emitsClickedId() = runTest(mainRule.dispatcher) {
    val clicks = Turbine<Long>()
    val adapter = ItemAdapter(onClick = clicks::add)

    adapter.bind(item)
    adapter.simulateClick()

    assertEquals(42L, clicks.awaitItem())
    clicks.ensureAllEventsConsumed()
}

适用场景

  • 被测类暴露 StateFlow<UiState> 或 SharedFlow<Event>,测试需要断言每次发射。
  • 测试在 SharedFlow 或 StateFlow 上使用 flow.toList() 时挂起(两者都不会完成)。
  • 需要断言"一段时间内没有更多发射"或"下一个事件是错误",而 toList() 无法表达。
  • 需要并发观察两个流(如 uiState 加一次性 events 流)并按交织顺序断言。

热流与冷流契约

  • 冷流(flowOf / flow { }):自然完成;第一个 awaitItem 返回首次发射;无需 cancel,awaitComplete 可终止。
  • MutableSharedFlow<T>(replay = 0):不完成;首个 awaitItem 返回下一次发射或挂起;始终需要 cancel。
  • MutableStateFlow<T>:不完成;首个 awaitItem 返回种子值(replay = 1);始终需要 cancel。

关键点:SharedFlow 与 StateFlow 永不调用 onCompletion,对它们调用 awaitComplete() 会等待到 3 秒墙钟超时。必须以 cancel() 或 cancelAndIgnoreRemainingEvents() 结束。

限制

  • 不适用于关于 runTest、TestScope、Dispatchers.setMain 或虚拟时间的测试;应先用 testing-coroutines-with-runtest 技能,Turbine 建立在其之上。
  • 若流是冷流且确定完成、断言为"完整列表等于 X",flow.toList() 更简短。
  • 若"flow"实为 Compose 快照状态,应通过测试规则读取,而非 Turbine。
  • Turbine 的 3 秒默认超时是墙钟时间,不受 TestCoroutineScheduler 驱动,也不遵循 runTest 的虚拟时间;若真实等待超过 3 秒,需通过 per-call timeout = 或 withTurbineTimeout 覆盖。

Turbine 支持多平台:JVM、Android、iOS、JS、Native、wasm;许可为 Apache 2.0,由 Square / Cash App 维护。技能来源为 skydoves/android-testing-skills。