Testing asynchronous code by sleeping produces slow suites that fail randomly on a loaded machine. The kotlinx-coroutines-test library removes the need entirely by replacing real time with virtual time.
runTest is the builder for a test body. Inside it, delay does not actually wait - the scheduler advances a virtual clock, so a function that delays for thirty seconds completes instantly while still exercising the real ordering. A test that takes milliseconds can cover timeouts and retries that would otherwise take minutes.
Control over execution comes from the scheduler. advanceUntilIdle runs everything queued until nothing is left. advanceTimeBy moves the clock a fixed amount, which is how you assert that something has not happened yet. runCurrent executes only the tasks scheduled at the current instant.
Two practical points. Inject the dispatcher rather than hard-coding Dispatchers.IO inside a class, or the test cannot substitute it - constructor injection with a default is the usual pattern. And for flows, either collect into a list inside the test or use the Turbine library, whose awaitItem makes emission-by-emission assertions readable.
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.test.*
import kotlin.test.Test
import kotlin.test.assertEquals
// The dispatcher is injected, so a test can substitute it
class Repository(private val dispatcher: CoroutineDispatcher = Dispatchers.IO) {
suspend fun load(): String = withContext(dispatcher) {
delay(30_000) // thirty seconds of real time
"loaded"
}
fun ticks(): Flow<Int> = flow {
repeat(3) { emit(it); delay(1_000) }
}
}
class RepositoryTest {
@Test
fun `load completes without waiting thirty seconds`() = runTest {
val repo = Repository(StandardTestDispatcher(testScheduler))
val result = async { repo.load() }
advanceUntilIdle() // virtual time jumps forward
assertEquals("loaded", result.await())
}
@Test
fun `ticks emits three values in order`() = runTest {
val collected = Repository().ticks().toList()
assertEquals(listOf(0, 1, 2), collected)
}
}
Discussion
No questions on this topic yet. Sign in to ask the first one.