gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 12:04:11 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com