如何在 ScalaTest 中显示自定义失败消息?
有谁知道如何在 ScalaTest 中显示自定义失败消息?
例如:
NumberOfElements() should equal (5)
失败时显示以下消息:
10 不等于 5
但我想要更多描述性消息,例如:
NumberOfElements 应为 5。
Does anyone know how to show a custom failure message in ScalaTest?
For example:
NumberOfElements() should equal (5)
Shows the following message when it fails:
10 did not equal 5
But i want more descriptive message like:
NumberOfElements should be 5.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您是第一个要求此类功能的人。实现此目的的一种方法是使用 withClue。类似的东西:
这应该会给你这个错误消息:
NumberOfElements: 10 was not equal to 5
如果你想完全控制该消息,你可以编写一个自定义匹配器。或者您可以使用断言,如下所示:
您能详细说明您的用例是什么吗?为什么 10 不等于 5 不合格,您多久有一次这种需要?
这是您要求的事情:
所以您可以这样写:
You're the first to ask for such a feature. One way to achieve this is with withClue. Something like:
That should get you this error message:
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:
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?
Here's the kind of thing you're requesting:
So this way you can write:
2011 年以来的新方法:
Matchers
和AppishedClue
1 特征。此外,对于集合大小,还有一些默认消息。输出如下所示:
请注意,
List
大小消息对于具有长.toString
输出的列表来说不太好。有关详细信息,请参阅 scaladoc。
1 我猜
AppishedClues
特征是受到这个问题的启发,接受的答案的 Bill Venners 是这个特征的作者。New way since 2011:
Matchers
andAppendedClue
1 traits. Also, for collection sizes, there are some default messages.Output looks like this:
Note that the
List
size message isn't great for lists with long.toString
output.See the scaladoc for more information.
1 I'm guessing the
AppendedClues
trait was inspired by this question, Bill Venners of the accepted answer is the author of this trait.您还可以使用
withClue
而不导入任何内容或将其添加到测试类:这是从
Assertions
类导入的:org.scalatest.Assertions#withClue
You can also use
withClue
without importing anything or adding it to the test class:This is imported from
Assertions
class:org.scalatest.Assertions#withClue
现有的答案都没有提到一些事情。
withClue
的位置决定了自定义消息的去向。如果写成withClue() {; }
,如果写成{; ,则 )
,附加message
会被添加到前面。 withClue(消息
。withClue
作为中缀运算符,必须混合org.scalatest.AppishedClues
,或者导入org.scalatest.AppishedClues.convertToClueful
。infix
关键字定义,Scala 3 不允许将名称完全按字母顺序排列的方法用作中缀。为了解决这个问题,请将withClue
括在反引号中,如下所示:{; }
`withClue`()
Few things that none of the existing answers mention.
withClue
determines where the custom message goes. If written aswithClue(<message>) { <assertion> }
, themessage
is prepended, if written as{ <assertion> } withClue(<message>)
, themessage
is appended.withClue
as an infix operator,org.scalatest.AppendedClues
must be mixed in, ororg.scalatest.AppendedClues.convertToClueful
imported.infix
keyword. In order to get around this, enclosewithClue
in backticks, like so:{ <assertion> }
`withClue`(<message>)