Strict coincidence in hamcrest?

I try to use Hamcrest, but constantly come across the following:

Hamcrest connectors are short-circuited, so for example, if I write:

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

Only the first erroneous shouldNotBeInList element is reported. I expect the tests will tell me as much as possible.

Can I write statements in hamcrest so that they are clearly reported, so that all inconsistencies are reported, or should I create my own interlocutors or use another library?

Output example for

 List<String> list = Arrays.asList("a", "b", "c"); List<String> shouldNotBeInList = Arrays.asList("c", "e", "a"); 

Note the error message for c

 Expected: every item is not one of {"c", "e", "a"} but: an item was "a" 
+1
source share
2 answers

Hamcrest is a bit more complicated when it comes to readable error messages. Some helpers create a useful message with all errors, others (most) report only the first error.

Of course, you could create your own matches with a β€œbetter” implementation and a good error message. Doing this for one or two matches is fine, but it can end with a Hamcrest override.

If you need another library, check out AssertJ . Statement

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

gives the following error message:

 Expecting <["a", "b", "c"]> not to contain <["c", "e", "a"]> but found <["c", "a"]> 
+2
source
 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); } } 

Expected: each element is not one of {"c", "e", "a"} but: the element was "a", the element was "c"

0
source

Source: https://habr.com/ru/post/1258090/


All Articles