Java – use Hamcrest-Matcher and assertThat() instead of traditional assertXXX()-Methods

hamcrestjavajunitjunit4testing

When I look at the examples in the Assert class JavaDoc

assertThat("Help! Integers don't work", 0, is(1)); // fails:
// failure message:
// Help! Integers don't work
// expected: is <1> 
// got value: <0>
assertThat("Zero is one", 0, is(not(1))) // passes

I dont see a big advantage over, let's say, assertEquals( 0, 1 ).

It's nice maybe for the messages if the constructs get more complicated but do you see more advantages? Readability?

Best Answer

There's no big advantage for those cases where an assertFoo exists that exactly matches your intent. In those cases they behave almost the same.

But when you come to checks that are somewhat more complex, then the advantage becomes more visible:

val foo = List.of("someValue");
assertTrue(foo.contains("someValue") && foo.contains("anotherValue"));
Expected: is <true>
         but: was <false>

vs.

val foo = List.of("someValue");
assertThat(foo, containsInAnyOrder("someValue", "anotherValue"));
Expected: iterable with items ["someValue", "anotherValue"] in any order
     but: no item matches: "anotherValue" in ["someValue"]

One can discuss which one of those is easier to read, but once the assert fails, you'll get a good error message from assertThat, but only a very minimal amount of information from assertTrue.