代码之家  ›  专栏  ›  技术社区  ›  John O'Reilly

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

  •  5
  • John O'Reilly  · 技术社区  · 7 年前

    已经开始尝试使用 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)
    }
    
    2 回复  |  直到 7 年前
        1
  •  11
  •   yigit    7 年前

    尝试将核心添加为测试的依赖项。它为我解决了问题。

    testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.1.0")

        2
  •  4
  •   John O'Reilly    7 年前

    问题是我使用的是旧版本的 kotlinx-coroutines-core