java编写自定义匹配器,与Hamcrest AllOf/CombinableMatcher匹配器配合使用
我试着写两个匹配词,这样就不用写了
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"
似乎有什么东西干扰了不匹配的文本。我希望“但是”这句话的意思是 但是:(状态代码为<;200>;,响应消息为“实际消息”)
从逻辑上讲,匹配器似乎工作正常
匹配者是:
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());
}
};
}
# 1 楼答案
这就是
AllOf
呈现不匹配的方式:它只显示第一个失败的Matcher
,其中its description followed by its description of the mismatch:考虑到结果将如何生成,在不匹配消息中添加额外的语言,如“不匹配,因为”,可能会让事情更清楚。Anopen pull request提出了一种方法,Hamcrest可以使描述更清晰,但也有不清楚的边缘情况
请参见Strange AllOf hamcrest matcher mismatch description了解关于现有匹配器而非自定义匹配器的类似问题