Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 565
Andrey Danilov Avatar asked Jul 28 '18 19:07

Andrey Danilov


1 Answers

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

like image 122
Andrey Danilov Avatar answered Oct 14 '22 16:10

Andrey Danilov