scala - 如何在 Scalatest 中为异步套件设置超时?
问题描述
考虑以下单元测试示例:
class MySpec extends AsyncFlatSpec {
"this" should "fail after some timeout" in {
val resultFuture: Future[_] = Promise().future
for (result <- resultFuture) yield {
assert(result == ???) // some assertions
assert(result == ???) // some assertions
assert(result == ???) // some assertions
}
}
}
问题
如果resultFuture
永远不会完成,那么测试套件也永远不会完成。据我了解,这是由于SerialExecutionContext
实施方式所致。
问题
有没有什么“好”的方法可以为这种测试设置超时,这样如果未来没有完成,测试就会失败,而不是永远阻塞整个测试套件?
更新和澄清
虽然解决方案https://stackoverflow.com/a/65746143/96766和https://stackoverflow.com/a/65749840/96766(由 @matthias-berndt 和 @tomer-shetah 发布)适用于线程阻塞的情况,这不是我要找的。
让我对这个问题做一个重要的澄清。在我的情况下,未来最终不会完成,但永远不会完成。例如,当 aFuture
是从Promise
从未解析的(没有人调用它success
也没有人调用failure
它)中获得时。在这种情况下,建议的解决方案仍然会无限阻塞。
有没有一种方法可以解决这个问题,AsyncSpec
而无需使用真正的基于池的执行上下文和Await
-ing 未来?
解决方案
使用eventually
自scalatest
- 延伸
Eventually
- 使用以下代码设置检查的超时和间隔
import scala.concurrent.duration._
eventually(timeout(1 minutes), interval(5 seconds)) {
resultFuture.futureValue shouldBe ???
}
推荐阅读
- python - 如何创建实时动态更新的无限动画帧?
- clojure - Clojure gorilla repl 和 JVM 10 异常
- android - 片段布局中的视图没有在正确的时间膨胀?
- python - 如果满足条件,则制作/保存图表,其中图表从 X 点开始
- jquery - 在列而不是行中写入表(扩展)
- mysql - 查询以计算表之间的多个总和
- sql-server - SQL Server:从字符串标题中获取列数据
- javascript - 数组拼接中的非唯一对象
- android - 如何在从 appCompat 视图扩展的视图中使用自定义字体
- javascript - 有什么更好的方法来设计句子生成器的内置统计功能?