Coroutines & Flow with Turbine

Testing suspend functions and Flows needs its own tools

Module 13 built LiveViewModel's state as a StateFlow β€” values arriving over time, not just once. A plain JUnit assertion can't wait for "the next emission"; it needs kotlinx-coroutines-test.

runTest is a coroutine test builder that runs on virtual time: a delay(30_000) inside the code under test doesn't actually pause the test for 30 real seconds β€” the virtual clock just skips forward instantly. That's what keeps a suite of coroutine tests fast even when the production code has real delays and retries built in. Under the hood runTest uses a TestDispatcher, which is what makes that time control possible in the first place.

For asserting on a Flow (or StateFlow) emission-by-emission, the Turbine library adds a .test { } block: inside it, awaitItem() suspends until the next value arrives and returns it, so you can assert against exactly what came out, in order.