This tutorial describes the usage of the AssertJ framework for writing unit tests in Java.

1. Introduction to AssertJ

The AssertJ project provides fluent assertion statements for test code written in Java. These assert statements are typically used with Java JUnit tests. The base method for AssertJ assertions is the assertThat method followed by the assertion.

AssertJ is a fork of the Fest assert library, as Fest is not actively maintained anymore.

Date today = new Date();

AssertJ assert statements try to create readable errors messages for test errors.

List<String> list = new ArrayList<>();
java.lang.AssertionError at ...

        to contain:
        but could not find:

2. Using AssertJ

As AssertJ is a Java library you can use Gradle or Maven to add it your project.

2.1. Gradle

To use AssertJ in your Gradle build for unit tests add the following dependency to your Gradle build file.

testimplementation 'org.assertj:assertj-core:3.20.2'

2.2. Maven

To use the library for a Maven based project, the following dependency to your pom file.


2.3. Eclipse IDE configuration

To simplify the usage of the AssertJ assertThat statement in the Eclipse IDE go to Window  Preferences  Java  Editor  Content assist  Favorites  New Type, enter org.assertj.core.api.Assertions and confirm.

You should see org.assertj.core.api.Assertions.* in the list.

2.4. IntelliJ Idea configuration

No special is needed configuration, just start typing assertThat and then invoke completion (Ctrl-Space) twice.

3. Usage of AssertJ

3.1. Writing assertions

AssertJ assertions start with a call to assertThat followed by an assertion.


3.2. Chaining of assertions

AssertJ allows you to be concise by chaining multiple assertions.

// JUnit style

// AssertJ

3.3. Assertions for Java collections

AssertJ comes with many built in matchers for Java collection classes.

For example the List class:

assertThat(userList).contains(user, atIndex(0)).containsOnlyOnce(user, user2, user3);

Here is an example that tests a Map:

// check for multiple keys at once
assertThat(map).containsKeys("a", "b", "c");
// check if the value of a certain key satisfies a condition
assertThat(map).hasEntrySatisfying(key, String::isEmpty);
// check if all entries of an other map are contained in a map

3.4. Assertions for Date

AssertJ provides special assertions for the Java date class.

assertThat(eclipseOxygen.getReleaseDate()).isBetween("2017-01-31", "2017-12-31");

3.5. Assertions for File and Stream

There are assertions to handle common file and stream checks.

// file assertions:

// stream assertions:

3.6. Adding a custom message to an assertion

We can add a customized message to existing assertions to better explain what we are expecting. For this purpose we use the as() method in our assertion chain:

User user = new User("admin");
assertThat(user.getPostCount()).as("User \"%s\" has no posts", user.getName()).isEqualTo(0);

3.7. Comparing objects field by field

Sometimes you don’t want to use the existing equals() method but just want to compare by certain fields. AssertJ provides multiple assertions to help you with that:

assertThat(user).isEqualToComparingOnlyGivenFields(otherUser, "address", "age");

If you have to problem the classes of certain fields don’t implement equals you can use isEqualToComparingFieldByFieldRecursively.


3.8. Further examples

The following example code is taken from the AssertJ homepage:

// unique entry point to get access to all assertThat methods and utility methods (e.g. entry)
import static org.assertj.core.api.Assertions.*;

// common assertions

// String specific assertions

// collection specific assertions
                               .contains(frodo, sam)

// using extracting magical feature to check fellowshipOfTheRing characters name :)
    .contains("Boromir", "Gandalf", "Frodo", "Legolas")
    .doesNotContain("Sauron", "Elrond");

// map specific assertions, ringBearers initialized with the elves rings and the one ring bearers.
                       .contains(entry(oneRing, frodo), entry(nenya, galadriel))
                       .doesNotContainEntry(oneRing, aragorn);

// and many more assertions : dates, file, numbers, exceptions ...

4. Converting JUnit assertions to AssrtJ with a script

The AssertJ project provides scripts for all major operating systems to automatically convert tests with JUnit assertions to AssertJ.

You can download them from their Github repository: Script for Unix/Windows Script for OSX

Just copy the script into the folder of the tests you want to convert and execute it.

# Unix/Windows
 1 - Replacing : assertEquals(0, myList.size()) ................. by : assertThat(myList).isEmpty()
 2 - Replacing : assertEquals(expectedSize, myList.size()) ...... by : assertThat(myList).hasSize(expectedSize)

While this script works pretty well it can still introduce compile errors that you have to fix manually. For more information on this topic please see the AssertJ project website.

5. Exercise: Creating a custom assertion for a class

While it is nice to have the ability to define custom error messages in the test, if we want to use this in multiple tests this can be come tedious and leads to redundant code. In this case it is useful to created custom assertion classes that are reusable. For this exercise we want to take our custom message example:

public void newlyCreatedUserHasNoPosts() throws Exception {
    User user = new User("admin");
    assertThat(user.getPostCount()).as("User \"%s\" has no posts", user.getName()).isEqualTo(0);

And transform it into this:

public void newlyCreatedUserHasNoPosts() throws Exception {
    User user = new User("admin");

5.1. Implementation

First we have to define our entry point class that lets us start the assertion chain. We have to provide a static assertThat method that returns our assertion class.

public class Assertions {

  public static UserAssert assertThat(User actual) {
    return new UserAssert(actual);

Now we create the missing assertion class.

public class UserAssert extends AbstractAssert<UserAssert, User> {

    public UserAssert hasNoPosts() {
          // check that actual User we want to make assertions on is not null.

          // overrides the default error message with a more explicit one
          String assertjErrorMessage = "\nExpecting User <%s> to have no posts\n but was:\n  <%s> posts";

          // null safe check
          int actualNumberOfPosts = actual.getPostCount();
          if (!Objects.areEqual(actualNumberOfPosts, 0)) {
            failWithMessage(assertjErrorMessage, actual.getName(), actualNumberOfPosts);

          // return the current assertion for method chaining
          return this;

    public UserAssert(User actual) {
        super(actual, UserAssert.class);

    public static UserAssert assertThat(User actual) {
        return new UserAssert(actual);


5.2. Validate

Now we can execute our test:

public void newlyCreatedUserHasNoPosts() throws Exception {
    User user = new User("admin");

Expecting User <admin> to have no posts
 but was:
  <42> posts

The AssertJ project provides generators that let you generate custom assertions from your existing Java classes in an automated way.

6. Using AssertJ Android

AssertJ Android allows you to write efficient assertions for Android. The following examples are taken from their Github page for AssertJ Android.

// check visibility of view with JUnit
assertEquals(View.GONE, view.getVisibility());

// AssertJ Androids version is much shorter

// AssertJ Android allows to combine checks

7. AssertJ resources