Method myLooper in android.os.Looper not mocked with Coroutines

非 Y 不嫁゛ 提交于 2019-12-22 08:48:15

问题


I want to do some test of coroutines in JUnit but I met some problems. Code is easy:

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

But I got that error

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)

The first thing I thought about was wrong coroutine context. So to be sure I used Unconfined but that doesnt work.

I`ve tried

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

But that doesn`t work too and I get following error:

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

But there is no Android main looper at all!

How can I run blocking coroutine in JUnit?


回答1:


Thanks Marko Topolnik for idea.

The problem is with 0.24.0 version of coroutines because of:

Attempts to use runBlocking from any supported UI thread (Android, JavaFx, Swing) will result in exception.

Unfortunately release has a bug with JUnit tests, so it doesnt let to use runBlocking in JUnit aswell.

Solution is changing version of coroutines to 0.23.4




回答2:


You can remove this check via an environment variable.

Either set it in your tests initilization:

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

Either set the env variable via Gradle with:

-Dkotlinx.coroutines.blocking.checker=disable


来源:https://stackoverflow.com/questions/51574486/method-mylooper-in-android-os-looper-not-mocked-with-coroutines

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