我正在尝试编写两个匹配器,以便代替编写
assertThat(response, hasStatusCode(OK));
assertThat(response, hasMessage("Some message."));
我可以写类似
的内容assertThat(response,
both(hasStatusCode(OK))
.and(hasMessage("Some message.")));
然而,当一个或两个匹配器失败时运行断言时,我得到了不合需要的奇怪输出:
Expected: (status code to be <200> and response to contain message "Some Message.")
but: response to contain message "Some Message." response message was "Actual message"
某些东西似乎在干扰不匹配的文字。我希望&#39;但是&#39;读取类似的东西 但是:(状态代码是&lt; 200&gt;并且响应消息是&#34;实际消息&#34;)
逻辑上,匹配器似乎工作正常。
匹配者是:
private Matcher<Response> hasMessage(final String expectedMessage) {
return new TypeSafeDiagnosingMatcher<Response>() {
@Override
protected boolean matchesSafely(final Response response, final Description mismatch) {
String message = response.getEntity().toString();
if (message != expectedMessage) {
mismatch.appendText("response message was ").appendValue(message);
return false;
}
return true;
}
@Override
public void describeTo(final Description description) {
description.appendText("response to contain message ").appendValue(expectedMessage);
}
};
}
private Matcher<Response> hasStatusCode(final Status expectedStatusCode) {
return new TypeSafeDiagnosingMatcher<Response>() {
@Override
protected boolean matchesSafely(final Response response, final Description mismatch) {
int statusCode = response.getStatus();
if (expectedStatusCode.getStatusCode() != statusCode) {
mismatch.appendText("status code was ").appendValue(statusCode);
}
return true;
}
@Override
public void describeTo(final Description description) {
description.appendText("status code to be ").appendValue(expectedStatusCode.getStatusCode());
}
};
}
答案 0 :(得分:1)
AllOf
表示不匹配的方式:它只显示第一个Matcher
失败,its description followed by its description of the mismatch:
if (!matcher.matches(o)) {
mismatch.appendDescriptionOf(matcher).appendText(" ");
matcher.describeMismatch(o, mismatch);
return false;
}
考虑如何生成结果,添加额外的语言,例如&#34;没有匹配,因为&#34;你的不匹配信息可能会使事情变得更清楚。 open pull request建议Hamcrest可以使描述更清晰,但也有不清楚的边缘情况。
有关类似问题,请参阅Strange AllOf hamcrest matcher mismatch description,围绕现有匹配器而不是自定义匹配器。