Error calling Dispatchers.setMain() in unit test

可紊 提交于 2019-12-08 17:33:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!