奇怪的AllOf hamcrest匹配器不匹配描述 [英] Strange AllOf hamcrest matcher mismatch description
问题描述
我正在使用 hamcrest 1.3 . matches(Object o, Description mismatch)
的实现如下:
I'm using hamcrest 1.3. Its implementation of matches(Object o, Description mismatch)
looks like that:
@Override
public boolean matches(Object o, Description mismatch) {
for (Matcher<? super T> matcher : matchers) {
if (!matcher.matches(o)) {
mismatch.appendDescriptionOf(matcher).appendText(" ");
matcher.describeMismatch(o, mismatch);
return false;
}
}
return true;
}
在描述不匹配时,它首先附加失败的匹配器的描述,然后才附加实际的不匹配.这样会产生一些非常奇怪的消息.
When describing mismatch, it first appends the description of matcher that failed, and only then the actual mismatch. This results in some pretty odd message.
例如,如果我写:
Description description = new StringDescription();
allOf(lessThan(2)).describeMismatch(5, description);
System.out.println(description.toString());
然后在控制台上打印a value less than <2> <5> was greater than <2>
.我希望仅<5> was greater than <2>
,因为这是其他匹配器返回的消息,例如lessThan
单独使用.
Then a value less than <2> <5> was greater than <2>
is printed the console. I would expect just the <5> was greater than <2>
, because that's the kind of message the other matchers return, e.g. lessThan
used alone.
我的问题是:这是错误还是我错过了什么?
My question being: is this a bug or am I missing something?
不同的匹配器以不同的格式返回消息这一事实非常重要,因为我试图编写一些使用匹配器的自定义验证框架,并且在出现任何问题时能够返回漂亮的人类可读消息.看来我不能为此目的使用describeMismatch
方法...
The fact that different matchers return messages in different formats is a big deal, since I was trying to write some custom validation framework that uses the matchers and is able to return nice human readable messages if anything goes wrong. It seems that I can't use the describeMismatch
method for that purpose...
推荐答案
我会说这是一个(可用性)错误.仅用单词"but"代替空格即可使消息更具表达力.
I'd say it's a (usability) bug. The message could be more expressive simply with the word "but" instead of the space.
值得指出的是,不匹配消息通常由JUnit的assertThat()显示,并带有其他一些单词:"Expected"(显示Matcher描述),"Actual"(显示不匹配).这样更清楚了.
It's worth pointing out that the mismatch messages are normally displayed by JUnit's assertThat() with some additional words: "Expected" (shows the Matcher description), "Actual" (shows the mismatch). This makes it clearer.
通常,当您使用allOf()时,您将拥有多个匹配器,因此对于失配描述来说,指出哪个中断是很有用的.但是我同意这个信息可能会更清楚.
Normally when you use an allOf() you'd have more than one matcher, so it's useful for the mismatch description to say which one broke. But I agree the message could be clearer.
这篇关于奇怪的AllOf hamcrest匹配器不匹配描述的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!