...

/

More on Testing Kotlin Coroutines

More on Testing Kotlin Coroutines

Learn about UnconfinedTestDispatcher, how to use mocks in testing, and the use of test functions that change a dispatcher.

UnconfinedTestDispatcher

Aside from StandardTestDispatcher, we also have UnconfinedTestDispatcher. The most significant difference is that StandardTestDispatcher does not invoke any operations until we use its scheduler. The UnconfinedTestDispatcher function immediately invokes all the operations before the first delay on started coroutines, which is why the code below prints “C.”

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

@ExperimentalCoroutinesApi
fun main() {
    CoroutineScope(StandardTestDispatcher()).launch {
        print("A")
        delay(1)
        print("B")
    }
    CoroutineScope(UnconfinedTestDispatcher()).launch {
        print("C")
        delay(1)
        print("D")
    }
}
Using UnconfinedTestDispatcher ( )

The runTest function was introduced in version 1.6 of the kotlinx-coroutines-test. Previously, we used runBlockingTest, whose behavior is much closer to runTest using UnconfinedTestDispatcher. So, ...