我在 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(...))
) 所做的是为隐式参数提供显式值。
实现您想要的效果的一种简单方法是执行以下操作:
- 从“最终调用”中删除所有显式
timeout()
。 创建一个特征以包含所需的超时默认值作为隐式值:
trait EventuallyTimeout { implicit val patienceConfig: PatienceConfig = PatienceConfig(timeout = ..., interval = ...)
将此特性混合到您的所有测试中:
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和 implicit .
最后,附带说明一下,eventually
主要用于集成测试。您可能需要考虑使用不同的机制,例如:
ScalaFutures
trait +whenReady
方法 - 类似于eventually
方法。- Async* 规范对应物(即 AsyncFunSpec、AsyncWordSpec 等)。
关于Scala 测试所有实现的最终配置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50646313/