【问题标题】:Writing custom matchers that play nicely with Hamcrest AllOf / CombinableMatcher matchers编写与 Hamcrest AllOf / CombinableMatcher 匹配器配合得很好的自定义匹配器
【发布时间】:2014-07-15 15:35:59
【问题描述】:

我正在尝试编写两个匹配器,而不是编写

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"

似乎有东西干扰了不匹配的文本。我希望“但是”行读到类似 但是:(状态代码是 并且响应消息是“实际消息”)

从逻辑上讲,匹配器似乎工作正常。

匹配器是:

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

【问题讨论】:

  • 您的回复似乎包含错误信息。你调试过吗?你有什么回应?
  • 你是什么意思?响应包含“实际消息”,而匹配器期待“预期消息”,因此应该(并且确实)失败。我已经修改了帖子以在“但是”的情况下包含预期的输出。我还注意到我粘贴的断言错误消息是针对稍有不同的测试,因此进行了相应修改(OK == 200 而不是 202)。

标签: java matcher hamcrest


【解决方案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;
}

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

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

【讨论】:

    猜你喜欢
    • 2023-04-04
    • 1970-01-01
    • 2013-04-26
    • 1970-01-01
    • 2015-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多