使用匹配器区分 ScalaTest 中的预期值和实际值
Distinguishing between expected and actual values in ScalaTest using matchers
在 ScalaTest 中,您可以使用 assertResult
宏来区分断言中的预期值和实际值,如下所示:
assertResult(expected) { actual }
这将在测试失败时打印“Expected X, but got Y
”消息,而不是通常的“X did not equal Y
”。
你如何使用(should
、must
等)匹配器实现类似的事情?
匹配器会构建自己的错误消息,因此对于标准匹配器,您只需要知道实际值就是左边的那个。如果你想改变消息,我相信你必须像 http://www.scalatest.org/user_guide/using_matchers#usingCustomMatchers 那样写一个自定义匹配器(下面的例子忽略了 TripleEquals
,等等):
trait MyMatchers {
class MyEqualMatcher[A](expectedValue: A) extends Matcher[A] {
def apply(left: A) = {
MatchResult(
left == expectedValue,
s"""Expected $expectedValue, but got $left""",
s"""Got the expected value $expectedValue"""
)
}
}
def equalWithMyMessage[A](expectedValue: A) = new MyEqualMatcher(expectedValue) // or extend Matchers and override def equal
}
// in test code extending the trait above
x should equalWithMyMessage(y)
在 ScalaTest 中,您可以使用 assertResult
宏来区分断言中的预期值和实际值,如下所示:
assertResult(expected) { actual }
这将在测试失败时打印“Expected X, but got Y
”消息,而不是通常的“X did not equal Y
”。
你如何使用(should
、must
等)匹配器实现类似的事情?
匹配器会构建自己的错误消息,因此对于标准匹配器,您只需要知道实际值就是左边的那个。如果你想改变消息,我相信你必须像 http://www.scalatest.org/user_guide/using_matchers#usingCustomMatchers 那样写一个自定义匹配器(下面的例子忽略了 TripleEquals
,等等):
trait MyMatchers {
class MyEqualMatcher[A](expectedValue: A) extends Matcher[A] {
def apply(left: A) = {
MatchResult(
left == expectedValue,
s"""Expected $expectedValue, but got $left""",
s"""Got the expected value $expectedValue"""
)
}
}
def equalWithMyMessage[A](expectedValue: A) = new MyEqualMatcher(expectedValue) // or extend Matchers and override def equal
}
// in test code extending the trait above
x should equalWithMyMessage(y)