如何从自定义 Mockito ArgumentMatcher 生成自定义消息?
我正在编写一个 ArgumentMatcher,比较的实质可以归结为:
return A.value().equals(B.value()) && A.name().equals(B.name());
不幸的是,当没有通过时,Mockito 只是告诉我它失败了。我想添加一条自定义消息,例如“值不匹配”或“名称不匹配”(当然我想提供更多信息,但在我弄清楚这个简单的情况之前,这样做有什么意义任何进一步)。
以前(在使用 Mockito 之前),我记得匹配器有两种方法 - 一种用于检查匹配,另一种用于生成失败消息(确实,编写这两种方法很痛苦,但我现在怀念第二种方法)。
知道如何做到这一点吗?任何帮助表示赞赏!
I'm writing an ArgumentMatcher and the guts of the comparison come down to something like:
return A.value().equals(B.value()) && A.name().equals(B.name());
Unfortunately, when the doesn't pass, Mockito just tells me it failed. I want to add a custom message like "Values don't match" or "Names don't match" (of course I'd like to give more info, but until I can figure out this simple case, what's the point of going any further).
Previously (before working with Mockito), I remember matchers having two methods - one to check the match and one to generate a failure message (true, it was a pain to write both methods, but I miss the second method now).
Any idea how to do this? Any help is appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我现在明白了。 Hamcrest 提供了“describeTo”方法。这和我记得的EasyMock的方法是等价的。您只需将错误条件添加到描述对象中,中提琴,您就会得到更好的失败消息。
I get it now. Hamcrest provides a "describeTo" method. This is equivalent to the method I remember from EasyMock. You simply add your error conditions to the Description object, and viola, you have a better failure message.
提供自定义消息的一般方法是通过
Mockito.description()
方法:A general way of providing custom messages is through
Mockito.description()
method:如果您正在实现 org.mockito.ArgumentMatcher 接口,测试将调用其 toString() 方法来创建比较消息的“Wanted”侧。通过简单地返回用于初始化
ArgumentMatcher
的预期对象的toString()
方法的值来实现此方法可能会为您带来有用的消息。If you are implementing the
org.mockito.ArgumentMatcher
interface, the test will call itstoString()
method to create the "Wanted" side of the comparison message. Implementing this method by simply returning the value of thetoString()
method on the expected object used to initialize theArgumentMatcher
will likely get you a useful message.我将 junit 断言扭曲为 argThat
它会给我有意义的消息,例如
I am warping junit assert into argThat
It will give me meaningful message like