如何在 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 never 完成,则测试套件也永远不会完成。 据我了解,这是由于 SerialExecutionContext 的实现方式造成的。

问题

有没有什么“好”的方法可以为这种测试设置超时,这样如果未来没有完成,测试就会失败,而不是永远阻塞整个测试套件?


更新和说明

虽然解决方https://stackoverflow.com/a/65746143/96766https://stackoverflow.com/a/65749840/96766(由@matthias-berndt 和@tomer-shetah 发布)适用于线程阻塞的情况,但这并不是我正在寻找的。​​p >

让我对这个问题做一个重要的澄清。就我而言,未来最终不会完成,而是永远完成。例如,当从从未解析的 Future 中获得 Promise 时(没有人对其调用 successfailure)。在这种情况下,建议的解决方案仍然无限阻塞。

有没有办法解决 AsyncSpec 的问题,而无需使用真正的基于池的执行上下文和 Await-ing 未来?

解决方法

使用 @media screen and (max-width: 1024px) and (min-width: 375px) {} @media screen and (max-width: 375px) {} 中的 eventually

  1. 扩展scalatest
  2. 使用下面的代码设置检查的超时时间和间隔
Eventually
,

使用 AsyncTimeLimitedTests 特性。

https://www.scalatest.org/scaladoc/3.2.0/org/scalatest/concurrent/AsyncTimeLimitedTests.html

,

您可以使用特征 TimeLimits。例如,您可以有一个测试类:

class MySpec extends AsyncFlatSpec with TimeLimits {

  "this" should "fail" in {
    failAfter(2.seconds) {
      val resultFuture: Future[_] = Future {
        Thread.sleep(3000)
      }

      assert(true)
    }
  }

  "this" should "pass" in {
    failAfter(2.seconds) {
      val resultFuture: Future[_] = Future {
        Thread.sleep(1000)
      }

      assert(true)
    }
  }
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...