92

有谁知道如何在 ScalaTest 中显示自定义失败消息?

例如:

NumberOfElements() should equal (5)

失败时显示以下消息:

10 不等于 5

但我想要更多描述性的消息,例如:

NumberOfElements 应为 5。

4

3 回答 3

110

您是第一个要求提供此类功能的人。实现这一目标的一种方法是使用 withClue。就像是:

withClue("NumberOfElements: ") { NumberOfElements() should be (5) }

这应该会给你这个错误消息:

NumberOfElements:10 不等于 5

如果您想完全控制消息,您可以编写自定义匹配器。或者你可以使用一个断言,像这样:

assert(NumberOfElements() == 5, "NumberOfElements should be 5")

你能详细说明你的用例是什么吗?为什么 10 不等于 5 不符合标准,您多久有过这种需求?

这是你要求的那种东西:

scala> import org.scalatest.matchers.ShouldMatchers._
import org.scalatest.matchers.ShouldMatchers._

scala> withClue ("Hi:") { 1 + 1 should equal (3) }
org.scalatest.TestFailedException: Hi: 2 did not equal 3
at org.scalatest.matchers.Matchers$class.newTestFailedException(Matchers.scala:150)
at org.scalatest.matchers.ShouldMatchers$.newTestFailedException(ShouldMatchers.scala:2331)


scala> class AssertionHolder(f: => Any) {
     |   def withMessage(s: String) {
     |     withClue(s) { f }
     |   }
     | }
defined class AssertionHolder

scala> implicit def convertAssertion(f: => Any) = new AssertionHolder(f)
convertAssertion: (f: => Any)AssertionHolder

scala> { 1 + 1 should equal (3) } withMessage ("Ho:")
org.scalatest.TestFailedException: Ho: 2 did not equal 3
at org.scalatest.matchers.Matchers$class.newTestFailedException(Matchers.scala:150)
at org.scalatest.matchers.ShouldMatchers$.newTestFailedException(ShouldMatchers.scala:2331)

所以这样你可以写:

{ NumberOfElements() should be (5) } withMessage ("NumberOfElements:")
于 2011-06-23T10:01:58.723 回答
13

自 2011 年以来的新方式:MatchersAppendedClue1 个特征。此外,对于集合大小,还有一些默认消息。

import org.scalatest.{AppendedClues, Matchers, WordSpec}

class SomeTest extends WordSpec with Matchers with AppendedClues {

  "Clues" should {
    "not be appended" when {
      "assertions pass" in {
        "hi" should equal ("hi") withClue "Greetings scala tester!"
      }
    }
    "be appended" when {
      "assertions fail"  in {
        1 + 1 should equal (3) withClue ", not even for large values of 1!"
      }
    }
    "not be needed" when {
      "looking at collection sizes" in {
        val list = List(1, 2, 3)
        list should have size 5
      }
    }
  }
}

输出如下所示:

SomeTest:
Clues
  should not be appended
  - when assertions pass
  should be appended
  - when assertions fail *** FAILED ***
    2 did not equal 3, not even for large values of 1! (SomeTest.scala:15)
  should not be needed
  - when looking at collection sizes *** FAILED ***
    List(1, 2, 3) had size 3 instead of expected size 5 (SomeTest.scala:21)

请注意,List大小消息不适用于具有长.toString输出的列表。

有关更多信息,请参阅scaladoc


1我猜这个AppendedClues特征是受到这个问题的启发,接受的答案的比尔文纳斯是这个特征的作者。

于 2018-04-18T01:25:45.503 回答
2

您也可以withClue在不导入任何内容或将其添加到测试类的情况下使用:

withClue(s"Expecting distinct elements: ${elements.toList}") { elements.length shouldBe 3 }

这是从Assertions类中导入的:org.scalatest.Assertions#withClue

于 2019-03-15T15:38:39.170 回答