John O'Reilly
John O'Reilly

Reputation: 10330

Error calling Dispatchers.setMain() in unit test

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)
}

Upvotes: 17

Views: 9902

Answers (2)

John O'Reilly
John O'Reilly

Reputation: 10330

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!)

Upvotes: 3

yigit
yigit

Reputation: 38243

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")

Upvotes: 18

Related Questions