Scalatest:组合断言
Scalatest: Combine Assertions
我刚开始使用 WordSpec,但遇到了一个无法解决的问题。
我想在一个单元测试中断言两个单独的值。假设我有 val result1
和 val result2
,我需要第一个取一个特定值,第二个取另一个特定值。
如果可以 concatenate/reduce/fold 断言,这将非常容易,但我认为我做不到。也许是这样的:
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
因为它可以更好地区分所断言的内容。但是,我发现一个潜在的缺点是,与 should be (x)
不同,returns Assertion
、Checkpoint#reportAll()
returns Unit
。我有一个需要 return Assertion
的方法,我使用的解决方法是 return org.scalatest.Succeeded
.
例如,
def someMethod(): Assertion = {
...
cp.reportAll()
Succeeded
}
我刚开始使用 WordSpec,但遇到了一个无法解决的问题。
我想在一个单元测试中断言两个单独的值。假设我有 val result1
和 val result2
,我需要第一个取一个特定值,第二个取另一个特定值。
如果可以 concatenate/reduce/fold 断言,这将非常容易,但我认为我做不到。也许是这样的:
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
因为它可以更好地区分所断言的内容。但是,我发现一个潜在的缺点是,与 should be (x)
不同,returns Assertion
、Checkpoint#reportAll()
returns Unit
。我有一个需要 return Assertion
的方法,我使用的解决方法是 return org.scalatest.Succeeded
.
例如,
def someMethod(): Assertion = {
...
cp.reportAll()
Succeeded
}