gpt4 book ai didi

scala - 如何在 ScalaTest 中显示自定义失败消息?

转载 作者:行者123 更新时间:2023-12-03 05:11:26 25 4
gpt4 key购买 nike

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

例如:

NumberOfElements() should equal (5)

失败时显示以下消息:

10 did not equal 5

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

NumberOfElements should be 5.

最佳答案

您是第一个请求此类功能的人。实现此目的的一种方法是使用 withClue。像这样的东西:

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

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

元素数量: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:")

关于scala - 如何在 ScalaTest 中显示自定义失败消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6451530/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com