Kotlin

Coroutine Testing with runTest

admin by @admin ADMIN
Jun 16, 2026
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
`runTest { }` from kotlinx-coroutines-test gives you a virtual time scheduler — `delay(1000)` finishes instantly while preserving ordering. No more flaky 1-second test sleeps.
Kotlin
Raw
// build.gradle.kts:
//   testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.7.+")

import kotlinx.coroutines.*
import kotlinx.coroutines.test.*
import kotlin.test.*

class UserService {
    suspend fun fetchUser(id: Int): String {
        delay(2000)         // simulate network
        return "User $id"
    }
}

class UserServiceTest {

    @Test
    fun fetches_user_eventually() = runTest {       // virtual time scheduler
        val service = UserService()
        val result = service.fetchUser(42)
        assertEquals("User 42", result)
        // Test finishes in ~0ms despite delay(2000) inside
    }

    @Test
    fun two_parallel_calls() = runTest {
        val service = UserService()
        val (a, b) = listOf(
            async { service.fetchUser(1) },
            async { service.fetchUser(2) },
        ).awaitAll().let { it[0] to it[1] }
        assertEquals("User 1", a)
        assertEquals("User 2", b)
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.