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

问题描述 投票:0回答:1

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

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

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

就代码而言,我执行以下操作:

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 并发实现吗?这将帮助我编写更多 DRY 代码。

做类似的事情

Eventually.default.timeout = 2.seconds

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

scala scalatest
1个回答
4
投票

本质上,您当前所做的

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
文档隐式

最后,顺便说一句,

eventually
主要用于集成测试。您可能需要考虑使用不同的机制,例如:

  1. ScalaFutures
    特质 +
    whenReady
    方法 - 类似于
    eventually
    方法。
  2. Async* 规范对应项(即 AsyncFunSpec、AsyncWordSpec 等)。
© www.soinside.com 2019 - 2024. All rights reserved.