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

Scala test eventually configuration for all implementations?

我在 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.seconds)...我想为所有测试配置一个配置,并有机会在特定情况下覆盖这个超时。

scala concurrent 最终可以实现吗?这将帮助我编写更多 DRY 代码。

做类似的事情

Eventually.default.timeout = 2.seconds

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

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

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

  1. 从`eventually call.
  2. 中删除所有明确的timeout()
  3. 创建特征以包含所需的超时默认值作为隐式值:

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

    }

  4. 将此特征混合到您的所有测试中:

    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 docs and implicit

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

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