作者:非洲小蘑菇bp | 来源:互联网 | 2022-12-09 12:33
我想在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中运行阻塞协同程序?
1> Andrey Danil..:
感谢Marko Topolnik的想法.
问题是0.24.0版本的协同程序,因为:
尝试从任何受支持的UI线程(Android,JavaFx,Swing)使用runBlocking将导致异常.
不幸的是发布有一个JUnit
测试错误,所以它不允许runBlocking
在JUnit中使用.
解决方案是将协同程序的版本更改为 0.23.4