Skip to Content
Course content

241: Testing Reactive Flows End to End

Click on the "Edit" button in the top corner of the screen to edit your slide content.

When you first start testing Kotlin Flows, it's tempting to treat them like standard lists. You have a stream of data, you want to see if a specific value comes out the other end, and you figure you can just "collect" it into a list and assert against that list. It seems straightforward until you realize that Flows are often infinite. If you try to collect a room's message stream in a test, your test will simply hang forever because the Flow never completes.

The "Hope and Pray" approach with manual collection

I've seen a lot of developers fall into the trap of manually launching a collection job in a separate coroutine and then using delay() to give the system time to process the event. It usually looks something like this:

testScope.launch {
    repository.messageFlow().collect { messages ->
        results.add(messages)
    }
}

repository.sendMessage("Hello World")
delay(100) // The "hope it worked" delay

assertEquals(1, results.size)
assertEquals("Hello World", results.first().last().text)

Here is why this is a nightmare in a professional codebase. First, those delay() calls are "magic numbers." On your high-end MacBook, 100ms is plenty. On a congested Jenkins or GitHub Actions runner, 100ms might not be enough, and suddenly you have a flaky test that fails once every ten builds for no apparent reason. Second, you're manually managing a Job. If you forget to cancel that collection coroutine, you're leaking resources, which can slow down your entire test suite as it grows.

Turning the stream into a queue with Turbine

Instead of trying to "catch" emissions in a mutable list, the better way is to treat your Flow as a queue of events that you can await. In the Kotlin ecosystem, the gold standard for this is a library called Turbine. It wraps the Flow and lets you "expect" items one by one. It fundamentally changes the test from "I hope this happened by now" to "I am waiting for this specific event to occur."

If we rewrite that same chat repository test using Turbine, the noise disappears:

repository.messageFlow().test {
    // First, we expect the initial empty state
    assertEquals(emptyList(), awaitItem())

    repository.sendMessage("Hello World")
    
    // Now we wait for the emission triggered by the send
    val updatedMessages = awaitItem()
    assertEquals("Hello World", updatedMessages.last().text)

    cancelAndIgnoreRemainingEvents()
}

Notice how the timing is handled implicitly. awaitItem() suspends the test until the Flow actually emits something or the timeout is reached. There is no guesswork. If the Flow never emits, the test fails immediately with a clear timeout error rather than just hanging or failing a vague assertion later on.

Handling the "Hot Flow" complexity

One thing to keep in mind is that end-to-end tests often deal with StateFlow or SharedFlow. These are "hot," meaning they exist independently of whether anyone is listening. If you start your Turbine .test { ... } block after you've already triggered an action, you might miss the emission entirely.

I always tell my teammates: start your test block first, then perform the action. This ensures you're subscribed to the stream before the event is fired. If you're testing a StateFlow, remember that it will always emit the current state immediately upon collection. If you don't account for that initial value with an awaitItem(), your assertions will be off by one, and you'll spend twenty minutes wondering why your "second" emission is actually the "first" one.




📋 Practical Task

Exercise: Debugging the Order-Tracking Stream

You have been handed a OrderRepository that exposes a Flow<OrderStatus>. The business logic dictates that when an order is placed, it must transition through three states: PENDING, SHIPPED, and DELIVERED.

The current test is written using the "naive" approach: it uses a mutableListOf() and delay(500), and it's currently flaking in CI because it sometimes only captures PENDING and SHIPPED before the assertion runs.

Your Task:

  • Remove the mutableListOf and the delay() calls.
  • Implement a Turbine .test { ... } block to verify the exact sequence of states.
  • Ensure the test verifies all three states (PENDING → SHIPPED → DELIVERED) in the correct order.
  • Verify that the test closes the flow properly using cancelAndIgnoreRemainingEvents().
Rating
0 0

There are no comments for now.

to be the first to leave a comment.