【问题标题】:Method myLooper in android.os.Looper not mocked with Coroutinesandroid.os.Looper 中的方法 myLooper 未使用 Coroutines 模拟
【发布时间】:2018-07-28 19:19:09
【问题描述】:

我想在 JUnit 中做一些协程测试,但遇到了一些问题。代码很简单:

@Test
fun coroutineTest() {
    //runBlocking(Unconfined) doesnt work too 
    runBlocking () {
        delay(1000)
        println("test")
    }
}

但我得到了那个错误

java.lang.RuntimeException: Method myLooper in android.os.Looper not mocked. See http://g.co/androidstudio/not-mocked for details.

at android.os.Looper.myLooper(Looper.java)
at kotlinx.coroutines.experimental.android.MainLooperChecker.checkRunBlocking(HandlerContext.kt:124)
at kotlinx.coroutines.experimental.BuildersKt__BuildersKt.runBlocking(Builders.kt:42)
at kotlinx.coroutines.experimental.BuildersKt.runBlocking(Unknown Source)
at app.deadmc.sometests.tests.ExampleUnitTest.coroutineTest(ExampleUnitTest.kt:22)

我首先想到的是错误的协程上下文。所以可以确定我使用了Unconfined,但这不起作用。

我试过了

android {
  // ...
  testOptions { 
    unitTests.returnDefaultValues = true
  }
}

但这也不起作用,我收到以下错误:

java.lang.IllegalStateException: runBlocking is not allowed in Android main looper thread

但是根本没有Android main looper

如何在 JUnit 中运行阻塞协程?

【问题讨论】:

标签: android junit kotlin kotlinx.coroutines


【解决方案1】:

感谢Marko Topolnik 的想法。

问题在于0.24.0 version of coroutines,因为:

尝试从任何受支持的 UI 线程(Android、 JavaFx, Swing) 会导致异常。

不幸的是,发布有一个JUnit 测试的错误,所以它也不允许在 JUnit 中使用runBlocking

解决方案是将协程版本更改为0.23.4

【讨论】:

【解决方案2】:

您可以通过环境变量删除此检查。

在你的测试初始化​​中设置它:

System.setProperty("kotlinx.coroutines.blocking.checker", "disable")

通过 Gradle 设置环境变量:

-Dkotlinx.coroutines.blocking.checker=disable

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-15
    • 2020-01-23
    • 1970-01-01
    • 2019-03-12
    相关资源
    最近更新 更多