我刚开始使用 WordSpec,但遇到了一个无法解决的问题。
我想在一个单元测试中断言两个独立的值。假设我有 val result1
和 val result2
,我需要第一个取一个特定值,第二个取另一个特定值。
如果可以连接/减少/折叠断言,这将非常容易,但我认为我做不到。也许是这样的:
result1 should be (1) ++ result2 should be (2)
结果将是一个新的断言,只有当两个断言都为真时才为真。
如果我把它们写成下面这样,它只会取最后一个值。
result1 should be (1)
result2 should be (2)
有人知道解决这个问题的方法吗?
最佳答案
对于 ScalaTest 3.0.1,我看到的两个选项是:
1.) 使用元组(正如@krzysztof-atłasik 评论的那样)
(result1, result2) should be (1, 2)
2.) 使用 Checkpoint
val cp = new Checkpoint()
cp { result1 should be (1) }
cp { result2 should be (2) }
cp.reportAll()
class Checkpoint, which enables multiple assertions to be performed within a test, with any failures accumulated and reported together at the end of the test.
-- ScalaTest 的检查点 scaladoc
就我个人而言,我喜欢 Checkpoint
,因为它可以更好地区分所断言的内容。然而,我发现一个潜在的缺点是,与返回 Assertion
的 should be (x)
不同,Checkpoint#reportAll()
返回 单位
。我有一个需要返回 Assertion
的方法,我使用的解决方法是返回 org.scalatest.Succeeded
.
例如,
def someMethod(): Assertion = {
...
cp.reportAll()
Succeeded
}
关于Scalatest:组合断言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61528075/