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?
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:
vs.
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 fromassertTrue
.assertThat
will tell you what the assertion was and what you got instead.assertTrue
will only tell you that you gotfalse
where you expectedtrue
.Basically for increasing the readability of the code.
Besides hamcrest you can also use the fest assertions. They have a few advantages over hamcrest such as:
(
assertEquals(123, actual); // reads "assert equals 123 is actual"
vsassertThat(actual).isEqualTo(123); // reads "assert that actual is equal to 123")
Some examples
October 17th, 2016 Update
Fest is not active anymore, use AssertJ instead.
A very basic justification is that it is hard to mess up the new syntax.
Suppose that a particular value, foo, should be 1 after a test.
--OR--
With the first approach, it is very easy to forget the correct order, and type it backwards. Then rather than saying that the test failed because it expected 1 and got 2, the message is backwards. Not a problem when the test passes, but can lead to confusion when the test fails.
With the second version, it is almost impossible to make this mistake.
there are advantages to assertThat over assertEquals -
1) more readable
2) more information on failure
3) compile time errors - rather than run time errors
4) flexibility with writing test conditions
5) portable - if you are using hamcrest - you can use jUnit or TestNG as the underlying framework.
Example:
btw: you can write Text in assertXXX too...
The JUnit release notes for version 4.4 (where it was introduced) state four advantages :
More detailed argumentation from the guy who created the new syntax : here.