views:

818

answers:

2

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?

+15  A: 

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:

assertTrue(foo.contains("someValue") && foo.contains("anotherValue"));

vs.

assertThat(foo, hasItems("someValue", "anotherValue"));

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.

assertThat will tell you what the assertion was and what you got instead. assertTrue will only tell you that you got false where you expected true.

Joachim Sauer
I had this question too in the back of my mind. Thank you, I never thought of it in this manner.
wheaties
It also helps with the "rule" of one assertion per test and blends more easily with BDD-style specifications.
springify
And it separates the assertion mechanism from the condition (which is what leads to the better error messages).
hbunny
+2  A: 

The JUnit release notes for version 4.4 (where it was introduced) state four advantages :

  • More readable and typeable: this syntax allows you to think in terms of subject, verb, object (assert "x is 3") rather than assertEquals, which uses verb, object, subject (assert "equals 3 x")
  • Combinations: any matcher statement s can be negated (not(s)), combined (either(s).or(t)), mapped to a collection (each(s)), or used in custom combinations (afterFiveSeconds(s))
  • Readable failure messages. (...)
  • Custom Matchers. By implementing the Matcher interface yourself, you can get all of the above benefits for your own custom assertions.

More detailed argumentation from the guy who created the new syntax : here.

Manur