Turbine
- Kotlin course
- Advanced
- Lesson 44/83
- 5 min
Learn Flow testing with Turbine.
Testing Flows with Turbine
Turbine is a library for testing Kotlin Flows. With flow.test { } you subscribe to the flow and use awaitItem and awaitComplete to wait for the next item and completion.
Example: val flow = flowOf(1, 2, 3); flow.test { assertEquals(1, awaitItem()); assertEquals(2, awaitItem()); awaitComplete() }. Turbine makes it easy to check items in order; it removes timing flakiness.
awaitItem and awaitComplete
awaitItem returns the next item emitted by the flow. awaitComplete verifies that the flow has completed. These two methods are the core of step-by-step flow testing.
Example: flow.test { val first = awaitItem(); val second = awaitItem(); awaitComplete() }. Each call to awaitItem gives the next item. If the order is wrong, the test fails. This guarantees items are emitted in the expected order.
Practice Test a Flow with Turbine
Define a function scoreFlow that returns flowOf(10, 20, 30). In main open a scoreFlow().test { } block and print each awaitItem() result with println.
Starter code
import kotlinx.coroutines.flow.flowOf
import app.cash.turbine.test
// scoreFlow function: emits three integers
// open a test block in main and print awaitItem resultsSample solution
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.Flow
import app.cash.turbine.test
fun scoreFlow(): Flow<Int> = flowOf(10, 20, 30)
fun main() = scoreFlow().test {
println(awaitItem())
println(awaitItem())
println(awaitItem())
}Expected output
10 20 30
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the .test block
val flow = flowOf(1, 2, 3)
flow.____ {
assertEquals(1, awaitItem())
awaitComplete()
}
val flow = flowOf(1, 2, 3)
flow.test {
assertEquals(1, awaitItem())
awaitComplete()
}
Explanation: flow.test { } subscribes and awaits items.
2 When testing a Flow with Turbine, which method returns the next emitted item?
- collect
- next
- awaitItem Correct answer
- fetch
Explanation: awaitItem returns the next item emitted by the flow.
3 Match the Turbine methods
| Term | Meaning |
|---|---|
flow.test { } |
Start subscription |
awaitItem() |
Next item |
awaitComplete() |
Completion |
expectNoEvents() |
No events |