Kotlin协程测试中如何测量挂起函数的总运行时长
如何测试包含计算和模拟延迟的挂起函数总时长
问题原因
你使用的testScheduler.timeSource.measureTime()是协程测试框架提供的模拟时间测量工具,它只会追踪协程调度中通过delay等API推进的模拟时间,完全忽略代码执行的真实CPU耗时,所以结果只等于函数中delay(1000)的时长。
解决方案
要同时获取真实计算耗时和模拟延迟时长并得到总时长,需要结合两种测量方式:
- 用
kotlin.system.measureTime()统计代码执行的真实CPU耗时(生成随机数的部分) - 用
TestCoroutineScheduler.currentTime获取模拟时间的变化量(即delay的时长)
最终总时长为两者之和,这样既跳过了真实延迟(测试不会等待1秒),又能得到你需要的“计算+延迟”总时长。
完整测试代码
@OptIn(ExperimentalTime::class) class SimpleTest { private val scheduler = TestCoroutineScheduler() private val dispatcher = StandardTestDispatcher(scheduler) private val scope = TestScope(dispatcher) @Test fun simpleTest() = scope.runTest { // 记录模拟时间初始值 val initialSimulatedTime = testScheduler.currentTime // 统计真实计算耗时(runTest会自动跳过delay的真实等待) val computationTime = kotlin.system.measureTime { randomNumberGeneratorWithDelay(10_000) } // 计算模拟延迟的时长 val simulatedDelayTime = testScheduler.currentTime - initialSimulatedTime // 总时长 = 真实计算耗时 + 模拟延迟时长 val totalDuration = computationTime + simulatedDelayTime // 根据实际计算耗时调整断言范围,比如计算耗时约0-10ms,总时长应在1000-1010ms之间 assert(totalDuration in 1000..1010) } }
补充说明
runTest会自动推进模拟时间,所以delay(1000)不会让测试真实等待1秒,保证测试速度computationTime的具体数值取决于随机数生成的次数和设备性能,断言时要留合理的误差范围- 如果函数中有多次
delay,testScheduler.currentTime的变化会累加所有模拟延迟的时长,无需额外处理
内容的提问来源于stack exchange,提问作者Jason
相关产品推荐
相关产品推荐

