RSS Feed Subscribe to RSS Feed


AssertJ > Fest > Hamcrest

I have previously blogged about Hamcrest, and using its assertThat methods in preference to JUnit’s Assert.

However, I quickly after discovered FEST Assertions, and happily switched to it. It provides the same improved test readability and failure messages as Hamcrest, but has the extra benefit of enabling IDE auto completion, rather than having to search through package and class docs to find the right matcher.

Unfortunately, Fest seems to not longer be actively developed. The last stable release of the 1.x branch, 1.4, was released way back in 2011, and the new 2.x branch never made it to a stable release and hasn’t had a commit since June 2013.

Enter AssertJ

Assert J

AssertJ is fork of Fest Assert, and seems to provide all the benefits plus a bunch of new features.


For example, it has all the nifty collections handling I so liked from Fest:

 List<String> stringList = Lists.newArrayList("A", "B", "C");
 assertThat(stringList).contains("A"); //true
 assertThat(stringList).doesNotContain("D"); //true
 assertThat(stringList).containsOnly("A"); //false
 assertThat(stringList).containsExactly("A", "C", "B"); //false
 assertThat(stringList).containsExactly("A", "B", "C"); //true

Collect all errors before failing

It also has the ability to catch all failures before failing. For example, the above example would fail as the first failed assumpion. The below example allows you to see all failed assertions:

 List<String> stringList = Lists.newArrayList("A", "B", "C");
 SoftAssertions softly = new SoftAssertions();
 softly.assertThat(stringList).contains("A"); //true
 softly.assertThat(stringList).containsOnly("A"); //false
 softly.assertThat(stringList).containsExactly("A", "C", "B"); //false
 softly.assertThat(stringList).containsExactly("A", "B", "C"); //true
 // Don't forget to call SoftAssertions global verification!

And results in a message like this:

The following 2 assertions failed:
 <["A", "B", "C"]>
to contain only:
elements not found:
and elements not expected:
 <["B", "C"]>
Actual and expected have the same elements but not in the same order, at index 1 actual element was:
whereas expected element was:

Definitely worth a look. AssertJ core code and issue tracker are hosted on github.

Tags: , , , ,

Leave a Reply