问题
Have started to try to use kotlinx-coroutines-test
(https://github.com/Kotlin/kotlinx.coroutines/blob/master/core/kotlinx-coroutines-test/README.md) in JUnit unit test but getting following error when i call 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)
I've tried calling Dispatchers.setMain(Dispatchers.Unconfined)
and also passing in val mainThreadSurrogate = newSingleThreadContext("UI thread")
. It looks like issue isn't anyway with value being passed in but rather it's tripping up in mainDispatcher
test in following
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)
}
回答1:
Try adding core as a dependency on your test. It solved the problem for me.
testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.1.0")
回答2:
Turned out issue was I was using older version of kotlinx-coroutines-core
dependency. When I updated to v1.1.0 it worked (thanks @vigit for helping trigger that realisation!)
来源:https://stackoverflow.com/questions/54061885/error-calling-dispatchers-setmain-in-unit-test