相关疑难解决方法(0)

在单元测试中调用Dispatchers.setMain()时出错

已开始尝试在JUnit单元测试中使用kotlinx-coroutines-test(https://github.com/Kotlin/kotlinx.coroutines/blob/master/core/kotlinx-coroutines-test/README.md)但在我调用时遇到以下错误Dispatchers.setMain()

java.lang.IllegalArgumentException: TestMainDispatcher is not set as main dispatcher, have Main[missing, cause=java.lang.AbstractMethodError: kotlinx.coroutines.test.internal.TestMainDispatcherFactory.createDispatcher()Lkotlinx/coroutines/MainCoroutineDispatcher;] instead.

    at kotlinx.coroutines.test.TestDispatchers.setMain(TestDispatchers.kt:22)
Run Code Online (Sandbox Code Playgroud)

我试过打电话Dispatchers.setMain(Dispatchers.Unconfined)也传入了val mainThreadSurrogate = newSingleThreadContext("UI thread").看起来似乎问题不是传递价值,而是mainDispatcher在接下来的测试中绊倒

public fun Dispatchers.setMain(dispatcher: CoroutineDispatcher) {
    require(dispatcher !is TestMainDispatcher) { "Dispatchers.setMain(Dispatchers.Main) is prohibited, probably Dispatchers.resetMain() should be used instead" }
    val mainDispatcher = Dispatchers.Main
    require(mainDispatcher is TestMainDispatcher) { "TestMainDispatcher is not set as main dispatcher, have $mainDispatcher instead." }
    mainDispatcher.setDispatcher(dispatcher)
}
Run Code Online (Sandbox Code Playgroud)

android coroutine kotlin kotlinx.coroutines

7
推荐指数
2
解决办法
1897
查看次数

标签 统计

android ×1

coroutine ×1

kotlin ×1

kotlinx.coroutines ×1