【问题标题】:Distinguishing between expected and actual values in ScalaTest using matchers使用匹配器区分 ScalaTest 中的预期值和实际值
【发布时间】:2016-09-16 06:27:25
【问题描述】:

在 ScalaTest 中,您可以使用 assertResult 宏来区分断言中的预期值和实际值,如下所示:

assertResult(expected) { actual }

这将在测试失败时打印“Expected X, but got Y”消息,而不是通常的“X did not equal Y”。

您将如何使用(shouldmust 等)匹配器实现类似的目标?

【问题讨论】:

    标签: scala scalatest


    【解决方案1】:

    匹配器构建自己的错误消息,因此对于标准匹配器,您只需知道实际值是左边的那个。如果您想更改消息,我相信您必须编写一个自定义匹配器,例如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)
    

    【讨论】:

    • 谢谢。可惜它没有内置到库中
    猜你喜欢
    • 2019-05-08
    • 1970-01-01
    • 2014-07-28
    • 1970-01-01
    • 1970-01-01
    • 2021-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多