android.os.Looper中的方法myLooper不与协程一起模拟 [英] Method myLooper in android.os.Looper not mocked with Coroutines

查看:186
本文介绍了android.os.Looper中的方法myLooper不与协程一起模拟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在JUnit中对协程进行一些测试,但是遇到了一些问题.代码很简单:

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

但是我得到了那个错误

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,但这是行不通的.

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

我尝试过

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

但是根本没有Android main looper

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

How can I run blocking coroutine in JUnit?

推荐答案

感谢 Marko Topolnik 的想法.

问题出在 0.24.0版本的协程因为:

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

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

不幸的是,发行版在JUnit测试中存在一个错误,因此不允许在JUnit中也使用runBlocking.

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

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

Solution is changing version of coroutines to 0.23.4

这篇关于android.os.Looper中的方法myLooper不与协程一起模拟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆