gpt4 book ai didi

java - 编写与 Hamcrest AllOf/CombinableMatcher 匹配器配合良好的自定义匹配器

转载 作者:太空宇宙 更新时间:2023-11-04 06:40:18 25 4
gpt4 key购买 nike

我正在尝试组成两个匹配器,这样就不用写了

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());
}
};
}

最佳答案

这就是 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;
}

考虑到结果的生成方式,在不匹配消息中添加额外的语言(例如“不匹配,因为”)可能会让事情变得更清楚。 open pull request 建议 Hamcrest 可以使描述更清晰,但也有不明确的边缘情况。

请参阅 Strange AllOf hamcrest matcher mismatch description 了解类似的问题,涉及现有匹配器而不是自定义匹配器。

关于java - 编写与 Hamcrest AllOf/CombinableMatcher 匹配器配合良好的自定义匹配器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24762380/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com