【发布时间】:2019-06-01 09:07:01
【问题描述】:
已开始尝试在 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)
我尝试调用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)
}
【问题讨论】:
标签: android kotlin coroutine kotlinx.coroutines