Testing coroutines and flows
Why it matters
- Tests that wait in real time (
Thread.sleep,runBlockingwith real delays, work on real background threads) are slow and flaky; virtual time makes them fast and deterministic. stateIn(WhileSubscribed)is a common source of "my flow test only sees the initial value" bugs, because the upstream never starts without a collector.- Interviewers probe dispatcher injection, the Standard vs Unconfined choice, and Turbine to see whether you understand how the test scheduler actually runs code.
- Unreliable tests get re-run and ignored, so real failures slip through with them.
The simple explanation
- Testing coroutines is like directing a film set.
- The wall clock is fake; the director controls it (virtual time in a
TestCoroutineScheduler). - Scenes wait in a queue until the director calls "action" (
runCurrent,advanceTimeBy,advanceUntilIdle). - A scene with no audience never starts (
WhileSubscribedneeds an active collector). - Every take runs in the same order, so the result is always the same (deterministic tests).
runTest creates a TestScope backed by a TestCoroutineScheduler. Code inside it runs on a StandardTestDispatcher by default, which queues new coroutines instead of running them at once. Queued work runs when the test body suspends (for example on awaitItem() or delay) or when you drive the scheduler yourself:
| Call | What it does |
|---|---|
runCurrent() | Runs tasks due at the current virtual time; the clock does not move |
advanceTimeBy(ms) | Runs tasks due before now + ms, then moves the clock there; call runCurrent() for tasks at exactly that time |
advanceUntilIdle() | Runs everything queued, jumping the clock forward, until nothing is left |
testScheduler.currentTime | The current virtual time in milliseconds |
A delay(5_000) inside runTest therefore finishes instantly in real time: when nothing else is ready, the scheduler jumps the virtual clock to the next task. At the end of the body, runTest keeps running queued work and waits for child coroutines to finish. If they never do, it fails after a real-time timeout (60 seconds by default in current versions; pass timeout to change it).
Two test dispatchers, and they only stay in step if they share one scheduler:
StandardTestDispatcher(testScheduler)queues work, so you can assert intermediate states such as Loading.UnconfinedTestDispatcher(testScheduler)starts new coroutines eagerly, up to their first suspension. It is handy for background collectors, but it hides ordering.
Production code should take its dispatchers as constructor parameters, so tests can pass a test dispatcher. viewModelScope always uses Dispatchers.Main, which does not exist in a JVM test, so replace it with Dispatchers.setMain(testDispatcher) in a JUnit rule (a MainDispatcherRule) and undo it with Dispatchers.resetMain(). When Main is a test dispatcher, runTest and test dispatchers created without a scheduler reuse Main's scheduler automatically.
Flows need a collector:
- Turbine:
flow.test { }collects the flow,awaitItem()suspends until the next value,expectNoEvents()fails if anything arrived, andcancelAndIgnoreRemainingEvents()stops collecting and drops what is left. When the block ends, Turbine cancels the collection and fails if events you never consumed are still waiting. - backgroundScope: a scope inside
runTestthat is cancelled when the test ends. Use it for collectors that never finish, such asbackgroundScope.launch { vm.uiState.collect() }; a plainlaunchwith an endless collector keepsrunTestwaiting until it times out.
For stateIn(scope, SharingStarted.WhileSubscribed(5_000), initial), the upstream runs only while at least one collector is active. Reading .value with no collector shows only the initial value.
Notes
- Use
runTestinstead ofrunBlockingin tests. It skipsdelaywith virtual time and waits for child coroutines before finishing. StandardTestDispatcheris the default insiderunTest. New coroutines wait until the test body suspends or you callrunCurrent(),advanceTimeBy(ms)oradvanceUntilIdle().advanceTimeBy(1_000)does not run a task scheduled at exactly 1,000 ms; follow it withrunCurrent().- Every test dispatcher in one test must share the same scheduler: pass
testScheduler, or create them afterDispatchers.setMainso they pick up Main's scheduler. UnconfinedTestDispatcherruns new coroutines eagerly. It is useful for collectors, but it can hide ordering bugs.- Put
Dispatchers.setMainandDispatchers.resetMainin aMainDispatcherRuleused as@get:Rule, so a failing test still restores Main. - Inject
CoroutineDispatcherparameters (defaulting toDispatchers.IOorDispatchers.Default) so tests can passStandardTestDispatcher(testScheduler)instead of a real thread pool. - Collect endless flows in
backgroundScope; it is cancelled automatically when the test body ends. - Turbine:
test { },awaitItem(),awaitError(),awaitComplete(),expectNoEvents(),cancelAndIgnoreRemainingEvents(). Unconsumed events at the end of the block fail the test. - A
stateIn(WhileSubscribed)flow needs an active collector in the test, from Turbine orbackgroundScope, or it never leaves its initial value. - Coroutine and flow tests belong in
src/test(JVM, no Android runtime).
Code example
A ViewModel that exposes a StateFlow built with stateIn(WhileSubscribed), a hand-written fake repository, a MainDispatcherRule, and three tests: two with Turbine and one with a backgroundScope collector.
// ---- Production code (src/main) ----
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
data class User(val name: String)
sealed interface UserUiState {
data object Loading : UserUiState
data class Success(val user: User) : UserUiState
data class Error(val message: String) : UserUiState
}
interface UserRepository {
fun observeUser(): Flow<User>
}
class UserViewModel(repository: UserRepository) : ViewModel() {
val uiState: StateFlow<UserUiState> = repository.observeUser()
.map<User, UserUiState> { UserUiState.Success(it) }
.catch { emit(UserUiState.Error(it.message ?: "Unknown error")) }
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), UserUiState.Loading)
}// ---- Test code (src/test) ----
import app.cash.turbine.test
import java.io.IOException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.emitAll
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.TestDispatcher
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.setMain
import org.junit.Assert.assertEquals
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TestWatcher
import org.junit.runner.Description
@OptIn(ExperimentalCoroutinesApi::class)
class MainDispatcherRule(
val testDispatcher: TestDispatcher = StandardTestDispatcher(),
) : TestWatcher() {
override fun starting(description: Description) = Dispatchers.setMain(testDispatcher)
override fun finished(description: Description) = Dispatchers.resetMain()
}
// Hand-written fake: the test decides what the repository emits and when
class FakeUserRepository : UserRepository {
private val users = MutableSharedFlow<User>(replay = 1)
var failure: Throwable? = null
fun send(user: User) {
users.tryEmit(user)
}
override fun observeUser(): Flow<User> = flow {
failure?.let { throw it }
emitAll(users)
}
}
@OptIn(ExperimentalCoroutinesApi::class)
class UserViewModelTest {
@get:Rule
val mainDispatcherRule = MainDispatcherRule()
private val repository = FakeUserRepository()
@Test
fun `emits loading then success`() = runTest {
val viewModel = UserViewModel(repository)
viewModel.uiState.test {
assertEquals(UserUiState.Loading, awaitItem())
repository.send(User("Alice"))
assertEquals(UserUiState.Success(User("Alice")), awaitItem())
}
}
@Test
fun `emits error when the repository fails`() = runTest {
repository.failure = IOException("offline")
val viewModel = UserViewModel(repository)
viewModel.uiState.test {
assertEquals(UserUiState.Loading, awaitItem())
assertEquals(UserUiState.Error("offline"), awaitItem())
}
}
@Test
fun `state updates only while someone collects`() = runTest {
val viewModel = UserViewModel(repository)
repository.send(User("Alice"))
runCurrent()
assertEquals(UserUiState.Loading, viewModel.uiState.value) // no collector yet
backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) {
viewModel.uiState.collect {}
}
runCurrent()
assertEquals(UserUiState.Success(User("Alice")), viewModel.uiState.value)
}
}- The rule replaces
Dispatchers.Mainbefore each test, soviewModelScopeworks on the JVM, andrunTestreuses the rule dispatcher's scheduler. - Turbine works with the
StandardTestDispatcher: whileawaitItem()suspends,runTestruns the queuedstateIncoroutine, which collects the fake and produces the next state. - The third test shows the
WhileSubscribedtrap directly:.valuestaysLoadinguntil a collector exists. The collector lives inbackgroundScope, so the test finishes even thoughcollectnever returns. - The fake replays its last user, so
sendbefore or after subscription both work. No MockK is needed, which matches the site's preference for fakes over mocks for repositories.
Run the idea in plain Kotlin
A tiny model of the test scheduler: tasks wait in a queue ordered by virtual time, and the three calls decide how far it runs. Note that advanceTimeBy(1000) stops before the task at exactly 1000 ms.
class Scheduled(val time: Long, val order: Int, val name: String, val block: () -> Unit)
// A tiny model of TestCoroutineScheduler: a queue of tasks ordered by virtual time
class VirtualScheduler {
var currentTime = 0L
private set
private val queue = mutableListOf<Scheduled>()
private var counter = 0
fun schedule(delayMs: Long, name: String, block: () -> Unit = {}) {
queue += Scheduled(currentTime + delayMs, counter++, name, block)
}
private fun runNext(limit: (Long) -> Boolean): Boolean {
val next = queue.filter { limit(it.time) }
.minWithOrNull(compareBy<Scheduled>({ it.time }, { it.order })) ?: return false
queue.remove(next)
currentTime = next.time
println(" t=" + currentTime + " ms: " + next.name)
next.block()
return true
}
// Runs only what is due now; the clock does not move
fun runCurrent() { while (runNext { it <= currentTime }) {} }
// Runs tasks due strictly before now + ms, then sets the clock to now + ms
fun advanceTimeBy(ms: Long) {
val target = currentTime + ms
while (runNext { it < target }) {}
currentTime = target
}
// Runs everything, jumping the clock forward as needed
fun advanceUntilIdle() { while (runNext { true }) {} }
}
fun main() {
val scheduler = VirtualScheduler()
var state = "Idle"
// A "ViewModel" launches work: Loading now, a network result after delay(1000)
scheduler.schedule(0, "set Loading") { state = "Loading" }
scheduler.schedule(1_000, "result arrives") {
state = "Success"
scheduler.schedule(5_000, "cache expires") { state = "Stale" }
}
println("after launch: " + state + " (StandardTestDispatcher queues the work)")
println("runCurrent()")
scheduler.runCurrent()
println("state = " + state + ", time = " + scheduler.currentTime)
println("advanceTimeBy(1000)")
scheduler.advanceTimeBy(1_000)
println("state = " + state + ", time = " + scheduler.currentTime + " (task at exactly 1000 not run yet)")
println("runCurrent()")
scheduler.runCurrent()
println("state = " + state + ", time = " + scheduler.currentTime)
println("advanceUntilIdle()")
scheduler.advanceUntilIdle()
println("state = " + state + ", time = " + scheduler.currentTime)
}Expected output:
after launch: Idle (StandardTestDispatcher queues the work)
runCurrent()
t=0 ms: set Loading
state = Loading, time = 0
advanceTimeBy(1000)
state = Loading, time = 1000 (task at exactly 1000 not run yet)
runCurrent()
t=1000 ms: result arrives
state = Success, time = 1000
advanceUntilIdle()
t=6000 ms: cache expires
state = Stale, time = 6000
In production
- A repository test used
runBlockinganddelay(200)to wait for work the repository ran on a hard-codedDispatchers.IO. - Tests passed on developer machines but failed now and then in CI, where the runner was slower.
- The team disabled the test, leaving the retry logic untested for several sprints.
- The repository now takes
ioDispatcher: CoroutineDispatcherin its constructor, defaulting toDispatchers.IO. - The test uses
runTest, passesStandardTestDispatcher(testScheduler), and callsadvanceUntilIdle()instead of waiting, so the retry delays are skipped in virtual time. - ViewModel tests got a shared
MainDispatcherRuleas a@get:Rule, so every test gets a cleanMaindispatcher.
- A developer called
vm.refresh(), then asserted onvm.uiState.valuefor aStateFlowcreated withstateIn(WhileSubscribed(5_000)). - The assertion always saw the initial
Loading, even though the fake repository had data. - The root cause:
WhileSubscribedstarts the upstream only when a collector exists, and the test had none.
- The test now collects the state with Turbine's
test { }and asserts eachawaitItem(). - Tests that prefer
.valuestartbackgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { vm.uiState.collect {} }first. - A short comment in the base test class explains why a collector is required, so the next person does not "fix" it by switching to
SharingStarted.Eagerly.
Common mistakes
- Using runBlocking instead of runTest. runBlocking has no virtual time, so every delay costs real time. Use runTest, which skips delays and fails cleanly on uncaught exceptions.
- Forgetting Dispatchers.setMain. Code that uses Dispatchers.Main, including viewModelScope, throws "Module with the Main dispatcher had failed to initialize" in a JVM test. Use a MainDispatcherRule.
- Creating test dispatchers with separate schedulers. A
StandardTestDispatcher()created before setMain, or a secondTestCoroutineScheduler, has its own clock, soadvanceUntilIdle()in the test never runs its work. PasstestScheduleror create dispatchers after setMain. - Launching an endless collector with plain launch.
launch { flow.collect {} }inside runTest never finishes, so runTest waits and fails after its timeout. UsebackgroundScope.launchfor collectors that run forever. - Hard-coding Dispatchers.IO in production code. The test cannot replace it, so the work runs on a real thread outside virtual time. Inject a CoroutineDispatcher with a default value.
- Leaving events unconsumed in Turbine. If the flow emits more than you awaited, Turbine fails at the end of the block. Await them, or call cancelAndIgnoreRemainingEvents() when the rest does not matter.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“What is the difference between StandardTestDispatcher and UnconfinedTestDispatcher?”
“Why does a stateIn(WhileSubscribed) flow not emit in a test?”
“How do you test a suspend function that uses a dispatcher and delays?”
“What happens if you forget Dispatchers.resetMain?”
Quiz
What does runTest do that runBlocking does not?
Inside runTest, a test calls launch { viewModel.uiState.collect {} } and the collector never completes. What happens?
What does cancelAndIgnoreRemainingEvents do in a Turbine test?
A task is scheduled at virtual time 1,000 ms. The clock is at 0 and the test calls advanceTimeBy(1_000). What is true?
0 of 4 answered
Mini task
15-minute exercise: test a ViewModel flow with Turbine
- In
src/main, createdata class Data(val name: String), aDataRepositoryinterface withfun observeData(): Flow<Data>, and a sealedDataStatewithLoading,Success(data: Data)andError(message: String). - Create
DataViewModel(repo: DataRepository) : ViewModel()exposingval state: StateFlow<DataState>: map toSuccess, add.catch { emit(DataState.Error(it.message ?: "error")) }, then.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), DataState.Loading). - In
src/test, add theMainDispatcherRulefrom the example and aFakeDataRepositorythat can emit data or throw. - Write three tests in
DataViewModelTest:emits loading then success: with Turbine, assertLoading, sendData("hello"), assertSuccess.emits error on failure: make the fake throwIOException("net")and assertLoadingthenError("net").stays Loading without a collector: send data, callrunCurrent(), and assertstate.valueis stillLoading; then collect inbackgroundScopeand assertSuccess.
- Run
./gradlew testDebugUnitTest.
Done condition: all three tests pass, there is no runBlocking, Thread.sleep or real Dispatchers.Main in the tests, and no test hangs until the runTest timeout.