如何在 ScalaTest 中显示自定义失败消息? [英] How to show custom failure messages in ScalaTest?

查看:45
本文介绍了如何在 ScalaTest 中显示自定义失败消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Does anyone know how to show a custom failure message in ScalaTest?

例如:

NumberOfElements() should equal (5)

失败时显示以下消息:

10 不等于 5

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

But i want more descriptive message like:

NumberOfElements 应该是 5.

NumberOfElements should be 5.

推荐答案

您是第一个要求这种功能的人.实现这一目标的一种方法是使用 withClue.类似的东西:

You're the first to ask for such a feature. One way to achieve this is with withClue. Something like:

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

那应该会给你这个错误信息:

That should get you this error message:

NumberOfElements: 10 不等于 5

NumberOfElements: 10 was not equal to 5

如果你想完全控制消息,你可以编写一个自定义匹配器.或者您可以使用断言,如下所示:

If you want to control the message completely you can write a custom matcher. Or you could use an assertion, like this:

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

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

Can you elaborate on what your use case is? Why is it that 10 did not equal 5 is not up to snuff, and how often have you had this need?

这是您要求的类型:

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:")

这篇关于如何在 ScalaTest 中显示自定义失败消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆