问题描述
我正在尝试对使用delay()
的Kotlin协程进行单元测试.对于单元测试,我不在乎delay()
,它只是在降低测试速度.我想以某种方式运行测试,该方式实际上不会在调用delay()
时延迟.
I'm trying to unit test a Kotlin coroutine that uses delay()
. For the unit test I don't care about the delay()
, it's just slowing the test down. I'd like to run the test in some way that doesn't actually delay when delay()
is called.
我尝试使用委托给CommonPool的自定义上下文运行协程:
I tried running the coroutine using a custom context which delegates to CommonPool:
class TestUiContext : CoroutineDispatcher(), Delay {
suspend override fun delay(time: Long, unit: TimeUnit) {
// I'd like it to call this
}
override fun scheduleResumeAfterDelay(time: Long, unit: TimeUnit, continuation: CancellableContinuation<Unit>) {
// but instead it calls this
}
override fun dispatch(context: CoroutineContext, block: Runnable) {
CommonPool.dispatch(context, block)
}
}
我希望我可以从上下文的delay()
方法中返回,但是它正在调用我的scheduleResumeAfterDelay()
方法,并且我不知道如何将其委派给默认的调度程序.
I was hoping I could just return from my context's delay()
method, but instead it's calling my scheduleResumeAfterDelay()
method, and I don't know how to delegate that to the default scheduler.
推荐答案
在kotlinx.coroutines v1.2.1中,他们添加了 kotlinx-coroutines-test 模块.它包括runBlockingTest
协程生成器以及TestCoroutineScope
和TestCoroutineDispatcher
.它们允许自动前进时间,并通过delay
明确控制测试协程的时间.
In kotlinx.coroutines v1.2.1 they added the kotlinx-coroutines-test module. It includes the runBlockingTest
coroutine builder, as well as a TestCoroutineScope
and TestCoroutineDispatcher
. They allow auto-advancing time, as well as explicitly controlling time for testing coroutines with delay
.
这篇关于延迟测试Kotlin协程的单元的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!