More on Testing Kotlin Coroutines
Explore advanced techniques for testing Kotlin coroutines. Understand how to use UnconfinedTestDispatcher and StandardTestDispatcher, apply mocks effectively, and verify dispatcher changes to ensure your coroutine functions behave as expected under test conditions.
We'll cover the following...
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")
}
}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, if we want to ...