对使用 withContext(Dispatchers.Main)
的 kotlin 挂起方法运行单元测试时测试方法失败,但有以下异常:
我的协程库版本是 kotlinx-coroutines-core:1.1.1 和 kotlinx-coroutines-android:1.1.1
示例:
suspend fun methodToTest() {
withContext(Dispatchers.Main) {
doSomethingOnMainThread()
val data = withContext(Dispatchers.IO) {
doSomethingOnIOThread()
}
}
}
另外,当我删除
withContext(Dispatchers.Main)
时它工作正常。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)
最佳答案
您无权在单元测试中访问 Dispatchers.Main
见 https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-test/Dispatchers.Main Delegation
部分详细说明了您需要做什么。
关于unit-testing - Kotlin 协程单元测试失败,错误为 "Module with the Main dispatcher had failed to initialize",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58303961/