While running unit test for kotlin suspend method which uses withContext(Dispatchers.Main)
the test method fails with below exception:
My coroutine lib versions are kotlinx-coroutines-core:1.1.1 and kotlinx-coroutines-android:1.1.1
Example:
suspend fun methodToTest() {
withContext(Dispatchers.Main) {
doSomethingOnMainThread()
val data = withContext(Dispatchers.IO) {
doSomethingOnIOThread()
}
}
}
Also, when I remove the withContext(Dispatchers.Main)
it works fine.
java.lang.IllegalStateException: Module with the Main dispatcher had failed to initialize. For tests Dispatchers.setMain from kotlinx-coroutines-test module can be used
at kotlinx.coroutines.internal.MissingMainCoroutineDispatcher.missing(MainDispatchers.kt:79)
at kotlinx.coroutines.internal.MissingMainCoroutineDispatcher.isDispatchNeeded(MainDispatchers.kt:54)
at kotlinx.coroutines.DispatchedKt.resumeCancellable(Dispatched.kt:373)
at kotlinx.coroutines.intrinsics.CancellableKt.startCoroutineCancellable(Cancellable.kt:25)
at kotlinx.coroutines.BuildersKt__Builders_commonKt.withContext(Builders.common.kt:152)
at kotlinx.coroutines.BuildersKt.withContext(Unknown Source)
You don't have access to Dispatchers.Main in unit testing
See https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-test/
Dispatchers.Main Delegation
part explains in detail what you need to do.