Loading...
Loading...
Use this skill to assert Flow emissions in tests with Cash App Turbine. Covers flow.test entry, ReceiveTurbine API (awaitItem, awaitComplete, awaitError, expectMostRecentItem, skipItems, expectNoEvents, cancel and friends, plus the non-suspending takeItem/takeComplete/takeError), turbineScope/testIn for multi-flow tests, the standalone Turbine<T> channel (add/close/asChannel/ensureAllEventsConsumed) for verifying non-Flow callbacks and listeners, the hot vs cold cancellation contract (StateFlow/SharedFlow never auto-complete), Turbine's wall-clock timeout decoupled from runTest virtual time, and the decision matrix between Turbine and raw flow.toList. If the user mentions Turbine, awaitItem, awaitComplete, expectMostRecentItem, takeItem, "test hangs on collect", "SharedFlow never completes", "StateFlow first emission", "TurbineAssertionError", "withTurbineTimeout", "Turbine() channel", "capture a callback in a test", or asserts a ViewModel's StateFlow/SharedFlow, use this skill.
npx skill4agent add skydoves/android-testing-skills testing-flows-with-turbinetoListFlowStateFlowSharedFlowflow.testReceiveTurbineturbineScopeflow.toList()../testing-coroutines-with-runtest/SKILL.mdStateFlow<UiState>SharedFlow<Event>flow.toList()SharedFlowStateFlowtoList()uiStateeventsTurbineAssertionError: Unconsumed events foundExpected an item but found Complete/ErrorawaitItemawaitCompleteawaitErrorexpectMostRecentItemskipItemsexpectNoEventswithTurbineTimeoutturbineScopetestInrunTestTestScopeDispatchers.setMain../testing-coroutines-with-runtest/SKILL.mdrunTestflow.toList()testImplementation("app.cash.turbine:turbine:1.x")docs/CORPUS.mdrunTest { … }suspendflow.test { }suspend@OptIn(ExperimentalCoroutinesApi::class)turbineScopeTestScope.backgroundScopepublic suspend fun <T> Flow<T>.test(
timeout: Duration = 3.seconds,
name: String? = null,
validate: suspend ReceiveTurbine<T>.() -> Unit,
)docs/CORPUS.mdtest { }flow.collect { }ReceiveTurbine<T>validate { }TestCoroutineSchedulerrunTestawaitItem()validate { }TurbineAssertionErrornamepublic interface ReceiveTurbine<T> {
// suspending
public suspend fun awaitItem(): T
public suspend fun awaitComplete()
public suspend fun awaitError(): Throwable
public suspend fun awaitEvent(): Event<T>
public suspend fun skipItems(count: Int)
public suspend fun cancel()
public suspend fun cancelAndIgnoreRemainingEvents()
public suspend fun cancelAndConsumeRemainingEvents(): List<Event<T>>
// non-suspending
public fun expectNoEvents()
public fun expectMostRecentItem(): T
public fun ensureAllEventsConsumed()
}| Call | Use when |
|---|---|
| Next event must be an item; fails on |
| Next event must be flow completion; fails on item/error. |
| Next event must be an error; returns the throwable for further assertions. |
| Sealed-class entry: |
| Drop n item events; fails if anything but an item is next. Useful to skip a |
| Non-suspending; drains buffered items and returns the latest. The "final state" assertion for |
| Non-suspending; throws if anything is buffered. Pair with |
| Stop the collector; any remaining events become an assertion failure on scope exit. |
| Stop, drain silently. The default tail of any hot-flow test. |
| Returns |
| Flow type | Completes naturally? | First | Need |
|---|---|---|---|
| yes | first emission | no — |
| no | next emission (or hangs) | always |
| no | seed value (replay = 1) | always |
docs/CORPUS.mdSharedFlowStateFlowonCompletionawaitComplete()cancel()cancelAndIgnoreRemainingEvents()StateFlow.testStateFlowreplay = 1skipItems(1)public suspend fun <R> turbineScope(
timeout: Duration? = null,
validate: suspend TurbineTestContext.() -> R,
): R
public fun <T> Flow<T>.testIn(
scope: CoroutineScope,
timeout: Duration? = null,
name: String? = null,
): ReceiveTurbine<T>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()
}
}testIncancel()awaitComplete()awaitError()turbineScopeTurbine<T>FlowTurbine<T>ReceiveTurbineFlow(T) -> UnitChannelpublic fun <T> Turbine(timeout: Duration? = null, name: String? = null): Turbine<T>
public interface Turbine<T> : ReceiveTurbine<T> {
public val isClosed: Boolean
public fun add(item: T) // producer side — push an item
public fun close(cause: Throwable? = null) // signal Complete (or Error if cause != null)
public fun asChannel(): Channel<T> // hand the producer a plain SendChannel
}docs/CORPUS.mdawaitItem()@Test fun emitsClickedId() = runTest(mainRule.dispatcher) {
val clicks = Turbine<Long>()
val adapter = ItemAdapter(onClick = clicks::add) // production code calls onClick(id)
adapter.bind(item)
adapter.simulateClick()
assertEquals(42L, clicks.awaitItem())
clicks.ensureAllEventsConsumed() // no extra invocations slipped through
}ensureAllEventsConsumed()flow.test { }TurbineawaitComplete()close()suspendtakeItemtakeCompletetakeError@TestassertsuspendReceiveTurbinepublic fun takeItem(): T
public fun takeComplete()
public fun takeError(): Throwable@Test fun synchronousDrain() = runTest(mainRule.dispatcher) {
val turbine = vm.uiState.testIn(backgroundScope)
advanceUntilIdle() // let the producer run to quiescence (virtual time)
assertEquals(Idle, turbine.takeItem()) // no suspension — the value is already buffered
assertEquals(Loaded, turbine.takeItem())
turbine.cancel()
}awaitItem()runTestflow.testtakeItem()runTestadvanceTimeBy(...)TestCoroutineSchedulerdelay(10.minutes)runTestflow.test { awaitItem() }flow.test(timeout = 10.seconds) { … } // per-call
withTurbineTimeout(10.seconds) { // scoped
flow.test { … }
}flow.toList()| Scenario | Pick |
|---|---|
| Cold flow that completes; "the full list equals X" | |
Hot | Turbine (handles cancellation) |
| Need to assert intermediate state then trigger more emissions | Turbine |
| Need to assert "no more events for a while" | Turbine ( |
| Need to assert error type / completion | Turbine ( |
| Multiple flows interleaved in one test | Turbine ( |
| Multiplatform test on JS/Native | Both work; Turbine is easier |
| Zero extra dependency | |
StateFlowflow.toList()flow.toList()// WRONG
@Test fun events() = runTest {
val events: SharedFlow<Event> = vm.events
val collected = events.toList() // never returns
assertEquals(listOf(LoggedIn), collected)
}
// WRONG because: SharedFlow never completes. toList() suspends until the upstream
// completes, which it never does. The test hangs to the 60s runTest timeout.// RIGHT
@Test fun events() = runTest(mainRule.dispatcher) {
vm.events.test {
vm.login()
assertEquals(LoggedIn, awaitItem())
cancelAndIgnoreRemainingEvents() // hot flow — must cancel
}
}// WRONG
@Test fun stateFlowEmits() = runTest(mainRule.dispatcher) {
vm.uiState.test {
vm.refresh()
assertEquals(Loading, awaitItem()) // FAIL: actually Idle (seed)
cancel()
}
}
// WRONG because: StateFlow has replay = 1. The collector immediately receives the
// current value (Idle) before any new emission. The first awaitItem() returns
// the seed, not the post-refresh state.// RIGHT — assert the seed
@Test fun stateFlowEmits() = runTest(mainRule.dispatcher) {
vm.uiState.test {
assertEquals(Idle, awaitItem()) // seed
vm.refresh()
assertEquals(Loading, awaitItem())
assertEquals(Success(items), awaitItem())
cancelAndIgnoreRemainingEvents()
}
}
// RIGHT — skip the seed if you do not care
@Test fun stateFlowEmits_skipSeed() = runTest(mainRule.dispatcher) {
vm.uiState.test {
skipItems(1)
vm.refresh()
assertEquals(Loading, awaitItem())
assertEquals(Success(items), awaitItem())
cancelAndIgnoreRemainingEvents()
}
}awaitComplete()// WRONG
@Test fun events() = runTest {
vm.events.test {
vm.login()
assertEquals(LoggedIn, awaitItem())
awaitComplete() // hangs 3s, then TurbineAssertionError
}
}
// WRONG because: SharedFlow never completes. awaitComplete() waits 3 wall-clock
// seconds (Turbine default) and then throws. The test is slow AND fails.// RIGHT
@Test fun events() = runTest(mainRule.dispatcher) {
vm.events.test {
vm.login()
assertEquals(LoggedIn, awaitItem())
cancelAndIgnoreRemainingEvents()
}
}expectMostRecentItem@Test fun finalState() = runTest(mainRule.dispatcher) {
vm.uiState.test {
skipItems(1) // seed
vm.flipFast() // posts 5 transitions in <1ms
advanceUntilIdle() // virtual; let coroutines settle
// StateFlow conflates — only the latest value is kept.
// awaitItem() may see anything from the burst; expectMostRecentItem is deterministic.
assertEquals(Final, expectMostRecentItem())
cancelAndIgnoreRemainingEvents()
}
}@Test fun noSpuriousEmissions() = runTest(mainRule.dispatcher) {
vm.uiState.test {
skipItems(1)
vm.refresh()
assertEquals(Loading, awaitItem())
assertEquals(Success(items), awaitItem())
advanceTimeBy(5.seconds) // virtual — flush any timers
runCurrent()
expectNoEvents() // confirms quiescence
cancelAndIgnoreRemainingEvents()
}
}// FINE — toList() is shorter for terminal cold flows
@Test fun coldList() = runTest {
val collected = flowOf(1, 2, 3).toList()
assertEquals(listOf(1, 2, 3), collected)
}
// ALSO FINE — Turbine if you need intermediate-state assertions
@Test fun coldTurbine() = runTest {
flowOf(1, 2, 3).test {
assertEquals(1, awaitItem())
assertEquals(2, awaitItem())
assertEquals(3, awaitItem())
awaitComplete() // cold flow — completes naturally
}
}turbineScope@Test fun interleaved() = runTest(mainRule.dispatcher) {
turbineScope {
val state = vm.uiState.testIn(backgroundScope, name = "state")
val events = vm.events.testIn(backgroundScope, name = "events")
assertEquals(Idle, state.awaitItem())
vm.login()
assertEquals(Loading, state.awaitItem())
assertEquals(LoggedIn, events.awaitItem())
assertEquals(Success, state.awaitItem())
state.cancel(); events.cancel()
}
}StateFlowSharedFlowflow.test { … cancelAndIgnoreRemainingEvents() }flow.toList()cancel()cancelAndIgnoreRemainingEvents()test { }awaitComplete()StateFlowawaitItem()skipItems(1)testImplementationapp.cash.turbineimplementationwithTurbineTimeout(...)timeout =runTestcancel()awaitComplete()testInturbineScoperunTestadvanceTimeBy(10.minutes)expectMostRecentItem()StateFlowflow.toList()flow.test(name = "uiState")flow.testIn(scope, name = "events")Turbine<T>()addcloseensureAllEventsConsumedMutableList(T) -> UnitawaitItem()awaitItem()runTestflow.testtakeItem()takeComplete()takeError()flow.toList()StateFlowSharedFlowgrep -rn 'toList()' src/testflow.test { … }cancel()cancelAndIgnoreRemainingEvents()awaitComplete()StateFlowSharedFlowStateFlowawaitItem()skipItems(1)withTurbineTimeout(...)timeout = N.secondsturbineScope { … testIn(backgroundScope) … }test { }Turbine<T>()ensureAllEventsConsumed()MutableListTurbineAssertionErrortasks/research/R5-coroutines-test-turbine.mdtoList()docs/CORPUS.md../testing-coroutines-with-runtest/SKILL.mdrunTestMainDispatcherRule../../mocking/mocking-with-mockito/SKILL.md../../mocking/mocking-with-mockk/SKILL.mdcoEvery { repo.items() } returns flowOf(...)../../runner/configuring-junit4-on-android/SKILL.md../../robolectric/using-robolectric-correctly/SKILL.md../../../fundamentals/strategies/applying-testing-strategies/SKILL.md../../../fundamentals/strategies/organizing-test-source-sets/SKILL.mdsrc/test/../../../compose/synchronization/controlling-the-test-clock/SKILL.mdMainTestClock../../../instrumentation/runner/running-instrumented-tests-with-androidjunit4/SKILL.md../../../kotlin/kotlin-test/writing-tests-with-kotlin-test/SKILL.mdawaitItem()kotlin.testassertEqualsassertIsflow.test { }