Testing coroutines
- Kotlin course
- Advanced
- Lesson 43/83
- 5 min
Learn coroutine testing with runTest.
Testing coroutines with runTest
runTest is a test builder in the kotlinx-coroutines-test library. It opens a TestScope to test suspend functions and uses virtual time instead of waiting in real time.
Example: @Test fun testFetch() = runTest { val result = fetchUser(1); assertEquals("Alex", result) }. Inside the runTest block, suspend calls are written like normal functions; delay is skipped instantly. This makes coroutine tests fast and deterministic.
TestScope and delay skipping
runTest returns a TestScope. Inside this scope, suspend functions are called like normal functions. delay calls are skipped automatically; there is no real waiting.
The kotlinx-coroutines-test dependency is required. Import it with import kotlinx.coroutines.test.runTest. Use assertEquals to check expected values. This pattern keeps coroutine tests fast and predictable.
Practice Test a suspend function with runTest
Define a suspend function fetchUser(id: Int): String that returns "Alex" when id is 1. In main open a runTest block and print the result of fetchUser(1) with println.
Starter code
import kotlinx.coroutines.test.runTest
// suspend function: returns Alex for id 1
// open a runTest block in main and print the resultSample solution
import kotlinx.coroutines.test.runTest
suspend fun fetchUser(id: Int): String {
return "Alex"
}
fun main() = runTest {
println(fetchUser(1))
}Expected output
Alex
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which of these can be done directly inside a runTest block?
- Only synchronous function calls
- suspend function calls Correct answer
- Only UI rendering
- Only file reads
Explanation: runTest provides a TestScope; suspend calls run directly.
2 Complete the runTest block
@Test
fun testFetch() = ____ {
val result = fetchUser(1)
assertEquals("Alex", result)
}
@Test
fun testFetch() = runTest {
val result = fetchUser(1)
assertEquals("Alex", result)
}
Explanation: runTest opens a TestScope for suspend functions.
3 Match the runTest parts
| Term | Meaning |
|---|---|
runTest { } |
Test builder |
TestScope |
Provided scope |
suspend fetch() |
Called function |
delay |
Skipped wait |