Unittesting: using AssertJ’s assertThat

JUnit4 provides a standard dependency to the Hamcrest Assertion Frameworks which makes the following assertions possible:

assertThat("Robbert",equalTo("Robbert"));

Many matchers beside equalTo are available, but the problem to me is that I always have search for the appropriate one that I want to use, and static import that matcher.

An alternative to Hamcrest, is AssertJ which provides a fluent interface for the assertions, so you can use your IDE’s code completion for searching the matchers.

AssertJ uses the following syntax:

assertThat("Robbert").isEqualTo("Robbert");

With AssertJ, it is also possible to use soft assertions which makes is possible to do multiple checks, and test all of them instead of stopping the test on the first failure.

SoftAssertions softly = new SoftAssertions();
softly.assertThat("Robert").isEqualTo("Robbert");
softly.assertThat("vd").isEqualTo("vd");
softly.assertThat("Zon").isEqualTo("Son");
softly.assertAll();

This results in the following error:

The following 2 assertions failed:
1) expected:<"Rob[b]ert"> but was:<"Rob[]ert">
at MyTest.test(MyTest.java:11) expected:<"Rob[b]ert"> but was:<"Rob[]ert">
2) expected:<"[S]on"> but was:<"[Z]on">
at MyTest.test(MyTest.java:13) expected:<"[S]on"> but was:<"[Z]on">

More about AssertJ can be found here:http://joel-costigliola.github.io/assertj/

To add a dependency to AssertJ, use the following:

testCompile("org.assertj:assertj-core:3.11.1")

or

<dependency>
    <groupId>org.assertj</groupId>
    <artifactId>assertj-core</artifactId>
    <version>3.11.1</version>
    <scope>test</scope>
</dependency>