我正在编写一个测试函数,它应该运行一个代码块,或者(当达到某个特定的超时时间)抛出异常。
我曾尝试使用 Kotlin 中的 Coroutines
,但最终得到了一种混合使用 Coroutines
和 CompletableFuture
的结果:
fun <T> runBlockWithTimeout(maxTimeout: Long, block: () -> T ): T {
val future = CompletableFuture<T>()
// runs the coroutine
launch { block() }
return future.get(maxTimeout, TimeUnit.MILLISECONDS)
}
这个方法可行,但我不确定这是否是在Kotlin中解决该问题的预期方式。
我还尝试了其他方法:
runBlocking {
withTimeout(maxTimeout) {
block()
}
}
但是当block
调用例如Thread.sleep(...)
时,这似乎不起作用。
那么,CompletableFuture
方法是正确的方法,还是有更好的方法?
更新1 我想要实现的目标:
异步集成测试代码(如从RabbitMq接收数据)应该像这样进行测试:
var rabbitResults: List = ... // are filled async via RabbitListeners
...
waitMax(1000).toSucceed {
assertThat(rabbitResults).hasSize(1)
}
waitMax(1000).toSucceed {
assertThat(nextQueue).hasSize(3)
}
...