We have a test suite that primarily uses JUnit assertions with Hamcrest matchers. One of our team started experimenting with AssertJ and impressed people with its syntax, fl
To add another option to Patrick M's answer:
Instead of using Descriptable.as
, you can also use AbstractAssert.withFailMessage():
try {
// set a bad age to Mr Frodo which is really 33 years old.
frodo.setAge(50);
// you can specify a test description via withFailMessage(), supports String format args
assertThat(frodo.getAge()).
withFailMessage("Frodo's age is wrong: %s years, difference %s years",
frodo.getAge(), frodo.getAge()-33).
isEqualTo(33);
} catch (AssertionError e) {
assertThat(e).hasMessage("Frodo's age is wrong: 50 years, difference 17 years");
}
The difference to using Descriptable.as
is that it gives you complete control over the custom message - there is no "expected" and "but was".
This is useful where the actual values being tested are not useful for presentation - this method allows you to show other, possibly calculated values instead, or none at all.
Do note that, just like Descriptable.as
, you must call withFailMessage()
before any actual assertions - otherwise it will not work, as the assertion will fire first. This is noted in the Javadoc.