有谁知道如何在ScalaTest中显示自定义失败消息?
例如:
NumberOfElements() should equal (5)
失败时显示以下消息:
10不等于5
但我想要更具描述性的信息,如:
NumberOfElements应为5。
答案 0 :(得分:87)
你是第一个要求这样一个功能的人。实现这一目标的一种方法是使用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:")
答案 1 :(得分:9)
自2011年以来的新方式:Matchers
和AppendedClue
特征。此外,对于集合大小,还有一些默认消息。
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。
答案 2 :(得分:1)
您也可以使用withClue
而不导入任何内容或将其添加到测试类中:
withClue(s"Expecting distinct elements: ${elements.toList}") { elements.length shouldBe 3 }
这是从Assertions
类:org.scalatest.Assertions#withClue