我编写了一个非常简单的减速函数,可以用来在不阻塞的情况下减缓响应。
suspend inline fun <T> slowdown(duration: Duration, block: () -> T): T {
var result: T
val timeTaken = measureTime {
result = block()
}
delay(duration - timeTaken)
return result
}在主工作中正确运行它。
fun main() = runBlocking {
val timeTaken1 = measureTime {
slowdown(2.seconds) {
delay(1000)
}
}
val timeTaken2 = measureTime {
slowdown(2.seconds) {
delay(4000)
}
}
println(timeTaken1) // 2.008962891s
println(timeTaken2) // 4.000145711s
}现在,我想编写一个测试用例来测试经济放缓,但实际上不需要2秒或4秒。
@Test
@ExperimentalCoroutinesApi
fun `ensure execution takes N seconds when operation takes N-t time`() = runTest {
val timeTaken1 = measureTime {
slowdown(2.seconds) {
delay(1000)
}
}
val timeTaken2 = measureTime {
slowdown(2.seconds) {
delay(4000)
}
}
println("========")
println(timeTaken1) // 9.472240ms
println(timeTaken2) // 131.839us
println("========")
}我假设measureTime和runTest玩得不好,但在delay上表现很好
如果我在测试中用Thread.sleep替换延迟
val timeTaken1 = measureTime {
slowdown(2.seconds) {
Thread.sleep(1000)
}
}
val timeTaken2 = measureTime {
slowdown(2.seconds) {
Thread.sleep(4000)
}
}然后打印出来
========
1.008311216s
4.000221902s
========delay(1000)在runTest下立即发生,但是measureTime也测量它是即时的,而不是被1秒所抵消。
我以为我可以用advanceTimeBy()破解它,但它似乎不影响measureTime。
将runTest更改为runBlocking是正确的,但它也会将测试速度分别降低到2秒和4秒。
是否有一个measureTime能很好地与runTest一起工作并在正常的runBlocking下工作?
发布于 2022-11-27 17:12:18
suspend fun <T> slowdown(duration: Duration, block: suspend () -> T): T = coroutineScope {
launch { delay(duration) }
block()
}@Test
@ExperimentalCoroutinesApi
fun `ensure execution takes N seconds when execution faster than N`() = runTest {
val currentTime1 = currentTime
slowdown(2.seconds) {
delay(1.seconds)
}
val currentTime2 = currentTime
assertEquals(2000, currentTime2 - currentTime1)
}
@Test
@ExperimentalCoroutinesApi
fun `ensure execution takes more than N seconds when execution slower than N`() = runTest {
val currentTime1 = currentTime
slowdown(1.seconds) {
delay(2.seconds)
}
val currentTime2 = currentTime
assertEquals(2000, currentTime2 - currentTime1)
}https://stackoverflow.com/questions/74584648
复制相似问题