Scala 测试所有实现的最终配置?

标签 scala scalatest

我在 scala 中有很多使用异步代码运行的测试,我最终正在使用 scala concurrent。这有助于我知道何时发生特定的异步事件,我可以期待特定的值。

但最终有一个可以为每个测试覆盖的超时,因此它不会因期待一个尚不存在的值而崩溃......

我想为最终的所有实现更改此超时,并为所有测试更改一个配置。

在代码方面我做了以下事情:

class AsyncCharacterTest extends WordSpec
  with Matchers
  with Eventually
  with BeforeAndAfterAll
  with ResponseAssertions {
  "Should provide the character from that where just created" should {
    val character = Character(name = "juan", age = 32)
    service.createIt(character)
    eventually(timeout(2.seconds)){ 
      responseAs[Character] should be character
    }
  }
}

我不想为每个测试都写这个超时(2.秒)...我想为所有测试配置一个配置,并有机会在特定情况下覆盖这个超时。

这最终可能与 scala concurrent 一起使用吗?这将帮助我编写更多 DRY 代码。

做类似的事情

Eventually.default.timeout = 2.seconds

然后这将同时对所有测试起作用,默认情况下为 2 秒。

最佳答案

本质上,您当前通过 eventually(timeout(...))) 所做的是为隐式参数提供显式值。

实现您想要的效果的一种简单方法是执行以下操作:

  1. 从“最终调用”中删除所有显式timeout()
  2. 创建一个特征以包含所需的超时默认值作为隐式值:

    trait EventuallyTimeout {
     implicit val patienceConfig: PatienceConfig = PatienceConfig(timeout = ..., interval = ...)
    

  3. 将此特性混合到您的所有测试中:

    class AsyncCharacterTest extends WordSpec extends EventuallyTimeout extends ...
    

完整示例:

// likely in a different file
trait EventuallyTimeout {
    implicit val patienceConfig: PatienceConfig = PatienceConfig(timeout = ..., interval = ...)
}

class AsyncCharacterTest extends WordSpec
  with Matchers
  with Eventually
  with BeforeAndAfterAll
  with ResponseAssertions 
  with EventuallyTimeout {
      "Should provide the character from that where just created" should {
        val character = Character(name = "juan", age = 32)
        service.createIt(character)
        eventually { 
          responseAs[Character] should be character
        }
      }
}

有关详细信息,请参阅 Eventually docsimplicit .

最后,附带说明一下,eventually 主要用于集成测试。您可能需要考虑使用不同的机制,例如:

  1. ScalaFutures trait + whenReady 方法 - 类似于eventually 方法。
  2. Async* 规范对应物(即 AsyncFunSpec、AsyncWordSpec 等)。

关于Scala 测试所有实现的最终配置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50646313/

相关文章:

scala - 使用 apache spark 和 scala 进行数据预处理

Scala 排序 map 没有方法 floor 或 ceil

java - Boyer-Moore 或 Java 或 Scala 库中的类似库

sbt - 仅从 sbt 运行特定的 Scalatest 测试

scala - 如何检查 Failure[T] 中包含哪个异常?

jquery - 在 scala.js 中实现 jquery-ui

scala - 如何从列表中删除 2 个或多个重复项并保持其初始顺序?

Scalacheck 嵌套 forall 在 Scalatest 测试失败时抛出 "oneOf called on empty collection"

java - 使用 scalatest 测试 Web 服务的 URI

scala - Intellij 不会运行 ScalaTests - "Incompatible Class Change Error"