0Pricing
Kotlin Academy · Lesson

Testing StateFlow and SharedFlow with Turbine

Write unit tests for Flow-based state using the Turbine testing library.

Why Turbine?

Turbine is a test library for Kotlin Flow that makes asserting emissions easy. Without it, testing flows requires manual channel collection with timeouts.

// Add to test dependencies:
// testImplementation("app.cash.turbine:turbine:1.0.0")
// testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.7.3")
import app.cash.turbine.*
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.test.*
fun main() { println("Turbine + runTest = clean flow testing") }

Basic Flow Testing with test()

flow.test { } collects the flow and lets you assert each emission using awaitItem(), awaitComplete(), and awaitError().

import app.cash.turbine.*
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.test.*
fun testBasicFlow() = runTest {
    val flow = flowOf(1, 2, 3)
    flow.test {
        assertEquals(1, awaitItem())
        assertEquals(2, awaitItem())
        assertEquals(3, awaitItem())
        awaitComplete()
    }
}

All lessons in this course

  1. StateFlow: Hot State Holder for UI
  2. SharedFlow: Event Buses and One-Shot Events
  3. Converting Cold Flow to Hot with shareIn and stateIn
  4. Testing StateFlow and SharedFlow with Turbine
← Back to Kotlin Academy