unit-testing - Kotlin 协程单元测试失败,错误为 "Module with the Main dispatcher had failed to initialize"

标签 unit-testing kotlin kotlin-coroutines

对使用 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/

相关文章:

kotlin - 如何在 Kotlin Actor 中获得非阻塞无限循环?

android - 模拟 android.os.Build.MODEL

android - 如何测试自定义 cordova 插件 native 代码?

java - 与单元测试 Controller 和服务方法的区别

java - 使用子类测试抽象类中的具体方法

android - lateinit RecyclerView是否需要在quickstart-android数据库应用中初始化?

kotlin - Kafka 使用 Kotlin 流式传输物化 View

kotlin - 如何通过ServiceLoader注册CoroutineExceptionHandler?

kotlin - 多少个协程就太多了?

java - 无法创建 AndroidViewModel 子类的实例