...

/

Functions Used in Testing Kotlin Coroutines

Functions Used in Testing Kotlin Coroutines

Discover more functions used while testing Kotlin coroutines.

Schedular property

The StandardTestDispatcher function creates TestCoroutineScheduler by default, so we don’t need to do so explicitly. We can access it with the scheduler property.

package kotlinx.coroutines.app
import kotlinx.coroutines.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.StandardTestDispatcher

@ExperimentalCoroutinesApi
fun main() {
    val dispatcher = StandardTestDispatcher()

    CoroutineScope(dispatcher).launch {
        println("Some work 1")
        delay(1000)
        println("Some work 2")
        delay(1000)
        println("Coroutine done")
    }

    println("[${dispatcher.scheduler.currentTime}] Before")
    dispatcher.scheduler.advanceUntilIdle()
    println("[${dispatcher.scheduler.currentTime}] After")
}
Using the scheduler property

Problem of StandardTestDispatcher

It’s essential to notice that StandardTestDispatcher does not advance time by itself. We need to do this; otherwise, our coroutine will never be resumed.

package kotlinx.coroutines.app
import kotlinx.coroutines.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.StandardTestDispatcher

@ExperimentalCoroutinesApi
fun main() {
    val testDispatcher = StandardTestDispatcher()

    runBlocking(testDispatcher) {
        delay(1)
        println("Coroutine done")
    }
}
// (code runs forever)
Problem of StandardTestDispatcher

Pushing time by using advanceTimeBy()

Another way to push time is using advanceTimeBy with a concrete number of milliseconds. This function advances time and executes all operations that happened in the meantime. If we push by two milliseconds, everything delayed by less than that time will be resumed. To resume operations ...