gpt4 book ai didi

android - Kotlin coroutines unit testing with runBlocking 不等待执行

转载 作者:行者123 更新时间:2023-11-29 23:22:22 26 4
gpt4 key购买 nike

有什么方法可以等待在范围内运行的挂起函数,就像 runBlocking 对其正在运行的挂起函数所做的那样?

例如,

class CoroutineTestCase : CoroutineScope {
val job = Job()
var value = 1
override val coroutineContext: CoroutineContext
get() = job + Dispatchers.Unconfined


fun testFunction() {
async {
delay(2000)
value = 2
}
}
}

@Test
fun testCoroutine() = runBlocking {
val coroutineTestCase = CoroutineTestCase()
coroutineTestCase.testFunction()
assertEquals(2, coroutineTestCase.value)
}

上述测试失败,值为 1 且未更改(因为未等待 launch 完成)。如果 testFunction 是一个挂起函数,并且我在单元测试中使用 runBlocking 运行它,一切都会正常。

我试过其他可以阻塞运行任务的自定义调度程序(如下所示),但没有成功

class TestUiContext : CoroutineDispatcher() {
override fun dispatch(context: CoroutineContext, block: Runnable) {
block.run()
}
}

最佳答案

好吧,我知道发生了什么。不会等待启动,因为它的返回值从未被使用过。

在上面的例子中,testFunction应该返回launch的返回值,这是一个可以等待/加入的Deffered对象。所以要真正等待它完成,代码必须更改如下:

class CoroutineTestCase : CoroutineScope {
val job = Job()
var value = 1
override val coroutineContext: CoroutineContext
get() = job + Dispatchers.Unconfined


fun testFunction(): Deferred<Unit> {
return async {
delay(20000)
value = 2
}
}
}

@Test
fun testCoroutine() = runBlocking {
val coroutineTestCase = CoroutineTestCase()
coroutineTestCase.testFunction().await()
assertEquals(2, coroutineTestCase.value)
}

目前唯一的问题是,在这种情况下,它实际上延迟了 20 秒(使用无限制调度程序)。

关于android - Kotlin coroutines unit testing with runBlocking 不等待执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54061539/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com