android - 延迟对 Kotlin 协程进行单元测试

我正在尝试对使用 delay() 的 Kotlin 协程进行单元测试。对于单元测试,我不关心 delay(),它只是减慢了测试速度。我想以某种在调用 delay() 时实际上不会延迟的方式运行测试。

我尝试使用委托(delegate)给 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() 方法,我不知道如何将其委托(delegate)给默认调度程序。

最佳答案

如果您不希望有任何延迟,为什么不简单地在调度调用中恢复继续?:

class TestUiContext : CoroutineDispatcher(), Delay {
    override fun scheduleResumeAfterDelay(time: Long, unit: TimeUnit, continuation: CancellableContinuation<Unit>) {
        continuation.resume(Unit)
    }

    override fun dispatch(context: CoroutineContext, block: Runnable) {
        //CommonPool.dispatch(context, block)  // dispatch on CommonPool
        block.run()  // dispatch on calling thread
    }
}

这样 delay() 将毫无延迟地恢复。请注意,这仍然会延迟暂停,因此其他协程仍然可以运行(例如 yield())

@Test
fun `test with delay`() {
    runBlocking(TestUiContext()) {
        launch { println("launched") }
        println("start")
        delay(5000)
        println("stop")
    }
}

无延迟运行并打印:

start
launched
stop

编辑:

您可以通过自定义 dispatch 函数来控制继续运行的位置。

https://stackoverflow.com/questions/47171302/

相关文章:

javafx - Kotlin 。基本 JavaFX 应用程序

android - kotlin 'onCreate' 不会覆盖任何内容

android - 为全屏 Activity 摆脱不必要的根布局

android - Kotlin 属性访问语法如何适用于 Java 类(即 EditText set

android - 应用程序模块中引用的 android 库模块的“ Unresolved 引用”错

android - "Extension with name ' android ' does no

java - 错误 :Kotlin: Unsupported plugin option: org.

android - 如何混淆我用 kotlin 编码的 sdk(并摆脱元数据)

spring - kotlin 和 @Valid Spring 注解

android - 如何在 kotlin 协程上进行指数退避重试