Kotlin
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Null Safety
-
Section 4: Object-Oriented Kotlin
-
Section 5: Functional Kotlin
-
Section 6: Coroutines
-
Section 7: Collections Deep Dive
-
Section 8: Type System Deep Dive
-
Section 9: Interop and Tooling
-
Section 10: Kotlin DSLs and Patterns
-
Section 11: Testing and Quality
-
Section 12: Server-Side Kotlin
-
Section 13: Practical Projects
-
Section 14: Interview Practice
-
Section 15: More Practice Exercises
-
Section 16: More Standard Library
-
Section 17: Multiplatform Kotlin
-
Section 18: kotlin.collections In Depth
-
Section 19: kotlin.text In Depth
-
Section 20: kotlin.ranges and kotlin.sequences
-
Section 21: kotlin.io and File Handling
-
Section 22: kotlinx.coroutines Deep Dive
-
Section 23: kotlin.reflect
-
Section 24: Android Development with Kotlin Overview
-
Section 25: Kotlin Multiplatform Deep Dive
-
Section 26: Kotlin for Backend Deep Dive
-
Section 27: Kotlin Design Patterns
-
Section 28: Advanced Language Features
-
Section 29: More Practice Exercises
-
Section 30: More Interview Practice
-
Section 31: Kotlin Type System Deep Dive
-
Section 32: Kotlin Null Safety Advanced
-
Section 33: Kotlin Testing Deep Dive
-
Section 34: Kotlin Build Tooling Deep Dive
-
Section 35: Kotlin Serialization
-
Section 36: Kotlin Performance Considerations
-
Section 37: Kotlin Native Overview
-
Section 38: Kotlin for Data and Scripting
-
Section 39: More Coroutines Practice
-
Section 40: More Android-Adjacent Patterns
-
Section 41: More Practical Projects
-
Section 42: More Design and Architecture Practice
-
Section 43: Kotlin Language Evolution
-
Section 44: More Interview and Review
-
Section 45: Kotlin Delegation Patterns Deep Dive
-
Section 46: Kotlin Annotations Deep Dive
-
Section 47: Kotlin for Gradle Plugin Development
-
Section 48: Kotlin Concurrency Beyond Coroutines
-
Section 49: Kotlin Compiler Internals
-
Section 50: Real-World Kotlin Case Studies
-
Section 51: Final Practice Projects
-
Section 52: Kotlin for Server-Side Reactive Programming
-
Section 53: More Practice and Drills
-
Section 54: Kotlin Security Practices
241: Testing Reactive Flows End to End
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
mutableListOfand thedelay()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().
There are no comments for now.