JavaHamcrest
JavaHamcrest copied to clipboard
hasSize and similar matchers to provide more debugging info
Consider the following test case:
@Test
public void asd() {
assertThat(Arrays.asList(57, 965), hasSize(greaterThan(3)));
}
When this guy fails, we'll get:
java.lang.AssertionError:
Expected: a collection with size a value greater than <3>
but: collection size <2> was less than <3>
Which is ok, but it doesn't provide much info in order to debug the failure. A more insightful output, I think, could be this:
java.lang.AssertionError:
Expected: a collection with size a value greater than <3>
but: collection size <2> was less than <3>
Actual collection:
- 57
- 965
By knowing what the array looked like at run time, it's more likely we'll be able to figure out what went wrong by just reading the error message.
This applies to any matcher dealing with the size of some data structure: hasSize, iterableWithSize, arrayWithSize.
In case the actual collection is very large, we should truncate it, as we don't want to pollute the output. We may save the full output to a text file for later consumption by the developer/tester:
java.lang.AssertionError:
Expected: a collection with size a value greater than <9000>
but: collection size <8999> was less than <9000>
Actual collection:
- 57
- 965
- 4394
- ... (truncated; please check the full content at /tmp/hamcrest/$timestamp)