Core Java

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 improves 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 a fork of Fest Assert, and seems to provide all the benefits plus a bunch of new features.

Collections

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 eample 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!
 softly.assertAll();

And results in a message like this:

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

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

Reference: AssertJ > Fest > Hamcrest from our JCG partner Shaun Abram at the Shaun Abram’s blog blog.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button