我正在尝试编写一个单元测试,等待kotlin挂起函数的完成,然后再检查如下结果:
@Test
fun shouldSetupThingsProperly() {
val context = InstrumentationRegistry.getInstrumentation().context
runBlocking { MyObject.enable(context, false) }
Assert.assertTrue( /* whatever usefull */ true)
}
暂停方法如下:
object MyObject {
@JvmStatic
suspend fun enable(context: Context, enable: Boolean) {
withContext(Dispatchers.IO) {
// ... do some work
wakeup(context)
}
}
private suspend fun wakeup(context: Context) {
withContext(Dispatchers.IO) {
try {
// setup things ...
} catch (ignore: Exception) {}
}
}
}
测试运行以以下方式结束:
java.lang.VerifyError: Verifier rejected class MyObject: java.lang.Object MyObject.enable(android.content.Context, boolean, kotlin.coroutines.Continuation) failed to verify: java.lang.Object MyObject.enable(android.content.Context, boolean, kotlin.coroutines.Continuation): [0x16] register v7 has type Reference: android.content.Context but expected Precise Reference: MyObject (declaration of 'MyObject' appears in /data/app/test-_rphd0tDrOp0KM-Bz09NWA==/base.apk!classes2.dex)
at MyObject.enable(Unknown Source:0)
我不熟悉协程,我想知道如何在测试中正确地实现等待启用挂起功能的完成,或者如果错误是由于某些其他错误所致……
发布于 2020-04-08 04:15:12
测试协程是一个技巧,即使在一些经验之后也是如此。如果你可以导入,这将是非常有用的:https://github.com/Kotlin/kotlinx.coroutines/tree/master/kotlinx-coroutines-test
如果你有了这种依赖测试,协程就变得更容易管理了。
首先,如果您可以让dispatcher运行一个可以设置或覆盖的变量或参数,它将帮助您提高可测试性。
就编写测试而言,您可以这样做:
@Before
fun before() {
Dispatchers.setMain(mainThreadSurrogate)
}
@Test
fun shouldSetupThingsProperly() = runBlockingTest {
val context = InstrumentationRegistry.getInstrumentation().context
MyObject.enable(context, false, Dispatchers.Main)
Assert.assertTrue( /* whatever useful */ true)
}
你的对象本身将会有更多的变化
object MyObject {
@JvmStatic
suspend fun enable(context: Context, enable: Boolean, dispatcher: CoroutineDispatcher = Dispatchers.IO) {
// If you need a return feel free to use withContext such as:
// val result = withContext(dispatcher) { /* Return Value */ Any() }
CoroutineScope(dispatcher).run {
// ... do some work
wakeup(context)
}
}
private suspend fun wakeup(context: Context) {
// Another coroutine scope is unnecessary here, it will inherit the parent scope automatically, so you can call
// async functions here
delay(200)
try {
// setup things ...
} catch (exc: Exception) {
// We had an issue
}
}
}
发布于 2020-07-28 20:19:04
如果它发生在Android或Flutter上的协程- withContext上,请将协程库恢复到1.3.6,为我解决了崩溃问题。在安卓协程库1.3.7-1.3.8版本中似乎存在VerifyError错误,将在1.4.0之后修复。
详情请参阅链接:
https://github.com/Kotlin/kotlinx.coroutines/issues/2049 https://github.com/Kotlin/kotlinx.coroutines/issues/2041
https://stackoverflow.com/questions/61087813
复制相似问题