Testing Coroutines & Flow
TESTING › Unit
Deterministically testing suspend functions, virtual time, dispatcher injection, and Flow emissions.
Interviewers use this to check whether you can write fast, deterministic coroutine tests instead of flaky thread-sleep tests. You are expected to know how runTest and TestScope control virtual time, why production dispatchers must be injected and Dispatchers.Main swapped out, and how to assert Flow emissions cleanly. ViewModel testing with fakes plus a test dispatcher rule is an extremely common live-coding prompt.
What this covers
- When and why to use runTest, TestScope, and the test TestCoroutineScheduler
- StandardTestDispatcher (queues coroutines) vs UnconfinedTestDispatcher (eager) and which to pick
- Driving virtual time with advanceUntilIdle, advanceTimeBy, and runCurrent so delays are skipped
- Injecting dispatchers and replacing the main dispatcher with Dispatchers.setMain / resetMain (MainDispatcherRule)
- Asserting Flow emissions with Turbine: awaitItem, awaitComplete, awaitError, and unconsumed-event failures
- Testing a ViewModel end to end with fake repositories plus a test dispatcher
Study this topic
- Testing Coroutines & Flow explained: the guided lesson
- 14 practice quiz questions
- 9 revision flashcards
- Testing Coroutines & Flow interview questions and answers