【发布时间】:2018-04-20 15:27:28
【问题描述】:
我正在尝试对使用 delay() 的 Kotlin 协程进行单元测试。对于单元测试,我不关心delay(),它只是减慢了测试速度。我想以某种在调用delay() 时实际上不会延迟的方式运行测试。
我尝试使用委托给 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() 方法,我不知道如何将其委托给默认调度程序。
【问题讨论】:
-
你不能把延迟超时设置成可配置的,这样在你的测试中你可以选择一个很小的吗?!
-
@s1m0nw1 是的,但我宁愿有一个通用的解决方案,而不必像那样修改我的代码。
-
@eoinmullan,你能分享一个最小的 git 项目吗?
标签: android unit-testing kotlin android-testing kotlin-coroutines