在hamcrest中严格匹配?

时间:2016-10-13 08:25:11

标签: java hamcrest

我试图使用Hamcrest,但不断遇到以下情况:

Hamcrest匹配器是短路的,因此,例如,如果我写:

 Assert.assertThat(list, everyItem(not(isIn(shouldNotBeInList))));

报告了shouldNotBeInList的第一个错误元素。我希望测试尽可能多地告诉我。

我是否可以在hamcrest中编写断言,他们报告的很好,以便报告所有不匹配,或者我应该创建自己的匹配器还是使用其他库?

的输出示例
List<String> list = Arrays.asList("a", "b", "c");
List<String> shouldNotBeInList = Arrays.asList("c", "e", "a");

请注意c

没有错误消息
Expected: every item is not one of {"c", "e", "a"}
     but: an item was "a"

2 个答案:

答案 0 :(得分:2)

Hamcrest在可读错误消息方面有点棘手。一些匹配器会创建包含所有错误的有用消息,其他匹配器(最多)仅报告第一个错误。

当然,您可以使用&#34;更好的&#34;创建自己的匹配器。实现和一个很好的错误消息。为一两个匹配器执行此操作是可以的,但这可能会重新实现Hamcrest。

如果您可以选择使用其他库,请查看AssertJ。断言

Assertions.assertThat(list).doesNotContainAnyElementsOf(shouldNotBeInList);

给出了以下错误消息:

Expecting
 <["a", "b", "c"]>
not to contain
 <["c", "e", "a"]>
but found
 <["c", "a"]>

答案 1 :(得分:0)

public static void main(String[] args) {
        List<String> list = Arrays.asList("a", "b", "c");
        List<String> shouldNotBeInList = Arrays.asList("c", "e", "a");

        Assert.assertThat(list, everyFullCheck(not(isIn(shouldNotBeInList))));
    }

    public static class EveryFullCheck<T> extends TypeSafeDiagnosingMatcher<Iterable<T>> {
        private final Matcher<? super T> matcher;

        public EveryFullCheck(Matcher<? super T> matcher) {
            this.matcher= matcher;
        }

        @Override
        public boolean matchesSafely(Iterable<T> collection, Description mismatchDescription) {
            boolean matches = true;
            for (T t : collection) {
                if (!matcher.matches(t)) {
                    if (!matches) {
                        mismatchDescription.appendText(", ");
                    }
                    mismatchDescription.appendText("an item ");
                    matcher.describeMismatch(t, mismatchDescription);
                    matches = false;
                }
            }
            return matches;
        }

        @Override
        public void describeTo(Description description) {
            description.appendText("every item is ").appendDescriptionOf(matcher);
        }
    }

    private static <U> EveryFullCheck<U> everyFullCheck(Matcher<? super U> matcher) {
        return new EveryFullCheck<>(matcher);
    }
        }
  

预期:每个项目都不是{&#34; c&#34;,&#34; e&#34;,&#34; a&#34;}        但是:一个项目是&#34; a&#34;,一个项目是&#34; c&#34;