This is now the official site for AssertJ Core replacing: http://joel-costigliola.github.io/assertj/assertj-core.html

The migration from the old site is still in progress but this new site already contains useful information and even some not documented previously!

If you feel something is missing or not clear enough, please raise an issue in https://github.com/assertj/doc/issues or even better contribute to it!

1. Overview

The goal of this document is to provide comprehensive reference documentation for programmers writing tests assertions with AssertJ.

1.1. What is AssertJ?

AssertJ is a java library providing a rich set of assertions, truly helpful error messages, improves test code readability and is designed to be super easy to use within your favorite IDE.

1.2. Getting Help

Ask AssertJ related questions on Stack Overflow.

2. AssertJ Core quick start

This guide is for the AssertJ core module.

AssertJ Core 2.x is in maintenance mode, it will only receive bugfixes.

2.1. Get assertj-core library

AssertJ Core artifacts are in the Maven central repository.

2.1.1. Supported Java versions

AssertJ Core major versions depend on different Java versions:

  • AssertJ Core 3.x requires Java 8 or higher

  • AssertJ Core 2.x requires Java 7 or higher

Note that AssertJ Core 3.x includes all AssertJ Core 2.x features and adds Java 8 specific ones (like exception assertions with lambdas).

2.1.2. Android support

AssertJ does not officialy supports Android but is mostly Android compatible:

  • AssertJ Core 3.x is compatible with Android API Level 26+, except for soft assertions and assumptions.

  • AssertJ Core 2.x is Android compatible with Android API Level 26+ and API Level < 26 except for Path assertions.

2.1.3. Maven

<dependency>
  <groupId>org.assertj</groupId>
  <artifactId>assertj-core</artifactId>
  <!-- use 2.9.1 for Java 7 projects -->
  <version>3.12.2</version>
  <scope>test</scope>
</dependency>

2.1.4. Gradle

For Gradle users (using the Maven Central Repository)

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

Or version 2.9.1 for Java 7 projects

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

2.1.5. Other dependency management tool

Check this page to find the relevant assertj core dependency declaration.

2.2. Use Assertions class

The Assertions class is the only class you need to start using AssertJ, it provides all the methods you need.

Alternatively your test class can implement WithAssertions to acccess the same methods.

One Assertions static import to rule them all …​

import static org.assertj.core.api.Assertions.*;

... or many if you prefer:

import static org.assertj.core.api.Assertions.assertThat;  // main one
import static org.assertj.core.api.Assertions.atIndex; // for List assertions
import static org.assertj.core.api.Assertions.entry;  // for Map assertions
import static org.assertj.core.api.Assertions.tuple; // when extracting several properties at once
import static org.assertj.core.api.Assertions.fail; // use when writing exception tests
import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; // idem
import static org.assertj.core.api.Assertions.filter; // for Iterable/Array assertions
import static org.assertj.core.api.Assertions.offset; // for floating number assertions
import static org.assertj.core.api.Assertions.anyOf; // use with Condition
import static org.assertj.core.api.Assertions.contentOf; // use with File assertions

On Android (API Level < 26) use this static import :

import static org.assertj.core.api.Java6Assertions.*;

You can configure your IDE so that when you start typing as and trigger code completion assertThat will show up in the suggested completions.

2.2.1. Eclipse configuration

  1. Go to : Window > Preferences > Java > Editor > Content Assist > Favorites > New Type

  2. Enter : org.assertj.core.api.Assertions and click OK

  3. Check that you see org.assertj.core.api.Assertions.* in Favorites.

2.2.2. Intellij Idea configuration

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

2.3. Use code completion

Type assertThat followed by the object under test and a dot …​ and any Java IDE code completion will show you all available assertions.

assertThat(objectUnderTest). (1)
1 Use IDE code completion after the dot.

Example for String assertions:

ide completion

3. Core assertions guide

This section describes the assertions provided by AssertJ Core and other useful features to get the best of it.

3.1. A simple example

Let’s start with a simple example showing a few important things.

import static org.assertj.core.api.Assertions.assertThat; (1)

import org.junit.jupiter.api.Test;

public class SimpleAssertionsExample {

  @Test
  void a_few_simple_assertions() {
    assertThat("The Lord of the Rings").isNotNull()  (2) (3)
                                       .startsWith("The") (4)
                                       .contains("Lord") (4)
                                       .endsWith("Rings"); (4)
  }

}
1 Statically import org.assertj.core.api.Assertions.assertThat
2 Pass the object under test as the sole assertThat() parameter
3 Use code completion to discover and call assertions
4 Chain as many assertions as you need

Except for isNotNull which is a base assertion, the other assertions are String specific as our object under test is a String.

3.2. Supported type assertions

AssertJ provides assertions specific to the object under test type, the following sections list the supported types grouped by categories.

The provided assertions for each of these types are documented later on.

3.2.1. Common types

BigDecimal

BigInteger

CharSequence

Class

Date

File

Future / CompletableFuture

InputStream

Iterable (including any kind of Collection)

Iterator

List

Map

Object

Object[]

  • Optional

  • OptionalInt / OptionalLong / OptionalDouble

Path

Predicate

Stream

String

Throwable / Exception

3.2.2. Primitive types

Primitive types and their wrapper:

  • short / Short

  • int / Integer

  • long / Long

  • byte / Byte

  • char / Character

  • float / Float

  • double / Double

Primitive type arrays:

  • short[]

  • int[]

  • long[]

  • byte[]

  • char[]

  • float[]

  • double[]

3.2.3. Java 8 Temporal types

Instant

LocalDate

LocalDateTime

LocalTime

OffsetDateTime

OffsetTime

3.2.4. Atomic types

Atomic basic types:

  • AtomicInteger,

  • AtomicLong

  • AtomicBoolean

Atomic array types:

  • AtomicIntegerArray

  • AtomicLongArray

Atomic reference types:

  • AtomicMarkableReference

  • AtomicStampedReferenceAssert

Atomic updater types:

  • AtomicIntegerFieldUpdater

  • AtomicLongFieldUpdater

  • AtomicReferenceFieldUpdater

3.3. Assertion description

It is often valuable to describe the assertion performed, especially for boolean assertions where the default error message just complains that it got false instead of true (or vice versa).

You can set such a description with as(String description, Object…​ args) but remember to do it before calling the assertion otherwise it is simply ignored as a failing assertion breaks the chained calls.

Example of a failing assertion with a description:

TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, Race.HOBBIT);

// failing assertion, remember to call as() before the assertion!
assertThat(frodo.getAge()).as("check %s's age", frodo.getName())
                          .isEqualTo(100);

The error message starts with the given description in [] :

[check Frodo's age] expected:<100> but was:<33>

3.4. Overriding error message

AssertJ tries its best to give helpful error messages but you always change it with overridingErrorMessage() or withFailMessage().

Example with this failing test:

TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, Race.HOBBIT);
TolkienCharacter sam = new TolkienCharacter("Sam", 38, Race.HOBBIT);
// failing assertion, remember to call withFailMessage/overridingErrorMessage before the assertion!
assertThat(frodo.getAge()).withFailMessage("should be %s", frodo)
                          .isEqualTo(sam);

The error message is:

java.lang.AssertionError: should be TolkienCharacter [name=Frodo, age=33, race=HOBBIT]

3.5. Avoiding incorrect usage

There are a few things to keep in mind when using AssertJ to avoid misusing it.

3.5.1. Forgetting to call an assertion

The main trap is to pass the object under to test to assertThat() and forget to call an assertion afterward. This misuse can be detected by SpotBugs or Findbugs thanks to the @CheckReturnValue annotation on all assertThat() methods.

Here’s what it looks like in SpotBugs:

SpotBugs detecting AssertJ invalid usage
Figure 1. SpotBugs detecting AssertJ invalid usage

The following examples show incorrect AssertJ API usage to avoid!

Bad

// DON'T DO THIS ! It does not assert anything
assertThat(actual.equals(expected));

Good

// DO THIS:
assertThat(actual).isEqualTo(expected);

// OR THIS (less classy but ok):
assertThat(actual.equals(expected)).isTrue();

Bad

// DON'T DO THIS ! It does not assert anything and passes
assertThat(1 == 2);

Good

// DO THIS: (fails as expected)
assertThat(1).isEqualTo(2);

// OR THIS (less classy but ok):
assertThat(1 == 2).isTrue();

3.5.2. Calling as() after the assertion

Describing an assertion must be done before calling the assertion otherwise it is ignored as a failing assertion breaks will prevent the call to as().

Bad

// DON'T DO THIS ! as/describedAs have no effect after the assertion
assertThat(actual).isEqualTo(expected).as("description");
assertThat(actual).isEqualTo(expected).describedAs("description");

Good

// DO THIS: use as/describedAs before the assertion
assertThat(actual).as("description").isEqualTo(expected);
assertThat(actual).describedAs("description").isEqualTo(expected);

3.5.3. Calling withFailMessage/overridingErrorMessage after the assertion

Setting an error message must be done before calling the assertion otherwise it is ignored as a failing assertion breaks will prevent the call to withFailMessage() / overridingErrorMessage().

Bad

// DON'T DO THIS ! overridingErrorMessage/withFailMessage have no effect after the assertion
assertThat(actual).isEqualTo(expected).overridingErrorMessage("custom error message");
assertThat(actual).isEqualTo(expected).withFailMessage("custom error message");

Good

// DO THIS: use overridingErrorMessage/withFailMessage before the assertion
assertThat(actual).overridingErrorMessage("custom error message").isEqualTo(expected);
assertThat(actual).withFailMessage("custom error message").isEqualTo(expected);

3.5.4. Setting a comparator after the assertion

Setting comparators must be done before calling the assertion otherwise it is ignored as a failing assertion breaks will prevent the call to usingComparator() / usingElementComparator().

Bad

// DON'T DO THIS ! Comparator is not used
assertThat(actual).isEqualTo(expected).usingComparator(new CustomComparator());

Good

// DO THIS:
assertThat(actual).usingComparator(new CustomComparator()).isEqualTo("a");

3.6. Controlling type formatting

Assertions error messages use a Representation to format the different types involved. There are multiple ways of registering a custom Representation for assertions:

The advantage of registering a service is that you don’t need any programmatic call, AssertJ will pick it up and use it as the default Representation.

Let’s go over these different options with a custom Representation.

3.6.1. Creating a custom Representation

An example of a custom Representation:

// dummy class
private class Example {}

public class CustomRepresentation extends StandardRepresentation { (1)

  // override fallbackToStringOf to handle Example formatting
  @Override
  public String fallbackToStringOf(Object o) { (2)
    if (o instanceof Example) return "Example";
    // fallback to default formatting.
    return super.fallbackToStringOf(o);
  }

  // override a predefined type formatting : String
  @Override
  protected String toStringOf(String str) { (3)
    return "$" + str + "$";
  }
}
1 Extends org.assertj.core.presentation.StandardRepresentation to get AssertJ default representation.
2 Override fallbackToStringOf and handle your specific types before falling back to the default formatting.
3 Change a predefined type formatting by overriding the toStringOf method that takes it as a parameter.

Let’s see the above custom representation in action when representing Example or String instances.

This assertion fails …​

assertThat(new Example()).isNull();

…​with the following error:

expected:<[null]> but was:<[Example]>

This one fails …​

// this one fails ...
assertThat("foo").startsWith("bar");

…​with the following error:

Expecting:
  <$foo$>
to start with:
  <$bar$>

3.6.2. Registering a default global scope custom representation

You will need to register your Representation as an SPI. You need to do the following for that:

  • Create a file named org.assertj.core.presentation.Representation in the META-INF/services directory

  • Put the fully qualified class name of your Representation in it

  • Make sure META-INF/services/org.assertj.core.presentation.Representation is in the runtime classpath, usually putting it in src/test/resources is enough

This all you have to do as AssertJ will pick up the Representation automatically.

3.6.3. Changing the default global scope custom representation

You only have to register CustomRepresentation once but need to do it before executing any tests, for the tests executed before that, AssertJ will use the default representation.

// to call before executing tests
Assertions.useRepresentation(new CustomRepresentation());

3.6.4. Per assertion scope custom representation

Follow this approach if you want to use a specific representation for a single assertion only.

Example with the failing assertions used before:

Representation customRepresentation = new CustomRepresentation();

// this assertion fails ...
assertThat(new Example()).withRepresentation(customRepresentation)
                         .isNull();

assertThat("foo").withRepresentation(customRepresentation)
                 .startsWith("bar");

3.7. Common assertions

This section describes the assertions common to all types.

3.8. Object assertions

TODO

3.9. Iterable/Collection assertions

TODO

3.10. Exception assertions

This chapter answers the question: how to assert that an exception has been thrown and check that it is the expected one ?

If you use java 8 or later versions, check the Java 8 section which heavily uses lambdas. If you use java 7, check the Java 7 section.

All the available assertions are described in the throwable assertions reference section.

In this chapter is exception is used interchangeably with throwable.

3.10.1. With Java 8 (AssertJ 3.x)

Thanks to lambdas testing assertions in Java 8 is elegant, AssertJ provides different style options:

where ThrowingCallable is a functional interface which can be expressed as a lambda.

BDD style

BDD aficionados can separate WHEN and THEN steps by using catchThrowable(ThrowingCallable) to capture the throwable and then perform assertions.

Example :

@Test
public void bdd_exception_assertion_example() {
   // GIVEN
   String[] names = { "Pier ", "Pol", "Jak" };
   // WHEN
   Throwable thrown = catchThrowable(() -> System.out.println(names[9]));
   // THEN
   assertThat(thrown).isInstanceOf(ArrayIndexOutOfBoundsException.class)
                     .hasMessageContaining("9");
}
BDD style on specific throwable type

This this a variation of catchThrowable where the caught exception type is specified allowing to check the custom exception fields/properties.

Example :

class TextException extends Exception {
   int line;
   int column;

   public TextException(String msg, int line, int column) {
     super(msg);
     this.line = line;
     this.column = column;
   }
 }

 TextException textException = catchThrowableOfType(() -> { throw new TextException("boom!", 1, 5); },
                                                    TextException.class);
 // assertions succeed
 assertThat(textException).hasMessageContaining("boom");
 assertThat(textException.line).isEqualTo(1);
 assertThat(textException.column).isEqualTo(5);

 // succeeds as catchThrowableOfType returns null when the code does not thrown any exceptions
 assertThat(catchThrowableOfType(() -> {}, Exception.class)).isNull();

 // fails as TextException is not a RuntimeException
 catchThrowableOfType(() -> { throw new TextException("boom!", 1, 5); }, RuntimeException.class);
Exception testing with assertThatThrownBy

Starts with assertThatThrownBy(ThrowingCallable) to capture and then assert on the thrown Throwable.

Note that if the provided ThrowingCallable does not raise an exception, an assertion error is immediately thrown.

Example :

@Test
public void exception_assertion_example() {
   assertThatThrownBy(() -> { throw new Exception("boom!"); }).isInstanceOf(Exception.class)
                                                              .hasMessageContaining("boom");
}
Exception testing with assertThatExceptionOfType

assertThatExceptionOfType is an alternative syntax that some people find more natural.

Note that if the code under test ThrowingCallable does not raise an exception, an assertion error is immediately thrown.

@Test
public void exception_assertion_example() {
   assertThatExceptionOfType(IOException.class).isThrownBy(() -> { throw new IOException("boom!"); })
                                               .withMessage("%s!", "boom")
                                               .withMessageContaining("boom")
                                               .withNoCause();
}

This later syntax has been enriched for common exceptions :

  • assertThatNullPointerException

  • assertThatIllegalArgumentException

  • assertThatIllegalStateException

  • assertThatIOException

The previous test can be rewritten as:

@Test
public void exception_assertion_example() {
   assertThatIOException().isThrownBy(() -> { throw new IOException("boom!"); })
                          .withMessage("%s!", "boom")
                          .withMessageContaining("boom")
                          .withNoCause();
}
Testing that no exception is thrown

You can test that a piece of code does not throw any exception with:

assertThatCode(() -> {
  // code that should NOT throw an exception
  ...
}).doesNotThrowAnyException();

3.10.2. Throwable reference assertions reference

Checking the exception message

There are two ways to check the exception message: hasMessage(String message) and hasMessage(String message, Object…​ parameters), the latter allows you to build the expected message as String.format.

Examples:

Throwable invalidArgException = new IllegalArgumentException("foo is not a valid input");
Throwable throwable = new Throwable(invalidArgException);

// This assertion succeeds:
assertThat(throwable).hasMessage("foo is not a valid input");
assertThat(throwable).hasMessage("%s is not a valid input", "foo");

// These assertions fail:
assertThat(throwable).hasMessage("bar is not a valid input");
assertThat(throwable).hasMessage("%s is not a valid input", "bar");

3.10.3. With Java 7 (AssertJ 2.x)

Asserting on exceptions is not as nice compared to the Java 8 way, this is how you would do it in AssertJ 2.x :

  1. Put the code to should throw in a try-catch.

  2. Call fail method immediately after the code that should throw the exception, so that if it is not thrown, the test fails.

  3. Make assertions on the caught exception

Note that fail method can be statically imported from Assertions class.

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown;
// ... code omitted for brevity

assertThat(fellowshipOfTheRing).hasSize(9);

// here's the typical pattern to use Fail :
try {
  fellowshipOfTheRing.get(9); // argggl !
  // we should not arrive here => use fail to expresses that
  // if IndexOutOfBoundsException was not thrown, test would fail the specified message
  fail("IndexOutOfBoundsException expected because fellowshipOfTheRing has only 9 elements");
} catch (IndexOutOfBoundsException e) {
  assertThat(e).hasMessage("Index: 9, Size: 9");
}

// Warning : don't catch Throwable as it would also catch the AssertionError thrown by fail method

// another way to do the same thing
try {
  fellowshipOfTheRing.get(9); // argggl !
  // if IndexOutOfBoundsException was not thrown, test would fail with message :
  // "Expected IndexOutOfBoundsException to be thrown"
  failBecauseExceptionWasNotThrown(IndexOutOfBoundsException.class);
} catch (IndexOutOfBoundsException e) {
  assertThat(e).hasMessage("Index: 9, Size: 9");
}

3.11. Field by field recursive comparison

Since 3.12.0 AssertJ Core provides a new fluent recursive comparison API for Object assertions, it is meant to replace isEqualToComparingFieldByFieldRecursively with more capabilities including:

This is a Beta version but it is worth using it already, we want to have feedback from the community to make it even better before freezing the API. There are more capabilities to come in the next releases, stay tuned!

The recursive comparison mode starts after calling usingRecursiveComparison(). By default it uses equals methods of classes that have overriden it, this can be changed and force recursive comparison on this classes (see this section).

Here’s a simple example to give an idea of what it can do:

public class Person {
  String name;
  double height;
  Home home = new Home();
}

public class Home {
  Address address = new Address();
  Date ownedSince;
}

public static class Address {
  int number;
  String street;
}

Person sherlock = new Person("Sherlock", 1.80);
sherlock.home.ownedSince = new Date(123);
sherlock.home.address.street = "Baker Street";
sherlock.home.address.number = 221;

Person sherlock2 = new Person("Sherlock", 1.80);
sherlock2.home.ownedSince = new Date(123);
sherlock2.home.address.street = "Baker Street";
sherlock2.home.address.number = 221;

// assertion succeeds as the data of both objects are the same.
assertThat(sherlock).usingRecursiveComparison()
                    .isEqualTo(sherlock2);

// assertion fails as Person equals only compares references.
assertThat(sherlock).isEqualTo(sherlock2);

The comparison is not symmetrical since it is limited to actual’s fields, the algorithm gather actual’s fields and then compare them to the corresponding expected’s fields. It is then possible for the expected object to have more fields than actual which can be handy when comparing a base type to a subtype with additional fields.

3.11.1. Strict or lenient comparison

By default the objects to compare can be of different types but must have the same properties/fields. For example if object under test has a work field of type Address, the expected object to compare the object under test to must also have one but it can of a different type like AddressDto.

It is possible to enforce strict type checking by calling withStrictTypeChecking() and make the comparison fail whenever the compared objects or their fields are not compatible. Compatible means that the expected object/field types are the same or a subtype of actual/field types, for example if actual is an Animal and expected a Dog, they will be compared field by field in strict type checking mode.

public class Person {
  String name;
  double height;
  Person bestFriend;
}

Person sherlock = new Person("Sherlock", 1.80);
sherlock.bestFriend = new Person("Watson", 1.70);

Person sherlockClone = new Person("Sherlock", 1.80);
sherlockClone.bestFriend = new Person("Watson", 1.70);

// assertion succeeds as sherlock and sherlockClone have the same data and types
assertThat(sherlock).usingRecursiveComparison()
                    .withStrictTypeChecking()
                    .isEqualTo(sherlockClone);

// Let's now define a data structure similar to Person

public class PersonDTO {
  String name;
  double height;
  PersonDTO bestFriend;
}

PersonDTO sherlockDto = new PersonDTO("Sherlock", 1.80);
sherlockDto.bestFriend = new PersonDTO("Watson", 1.70);

// assertion fails as Person and PersonDTO are not compatible even though they have the same data
assertThat(sherlock).usingRecursiveComparison()
                    .withStrictTypeChecking()
                    .isEqualTo(noName);

// Let's define a subclass of Person

public class Detective extends Person {
  boolean busy;
}

Detective detectiveSherlock = new Detective("Sherlock", 1.80);
detectiveSherlock.bestFriend = new Person("Watson", 1.70);
detectiveSherlock.busy = true;

// assertion succeeds as Detective inherits from Person and
// only Person's fields are included into the comparison.
assertThat(sherlock).usingRecursiveComparison()
                    .withStrictTypeChecking()
                    .isEqualTo(detectiveSherlock);

3.11.2. Ignoring fields in the comparison

It is possible to ignore fields of the object under test in the comparison, this is can be useful when a field has a generated value (like the current time) or is simply not relevant to compare.

There are a few ways to specify the fields to ignore:

  • directly with ignoringFields(String…​ fieldsToIgnore)

  • by regexes with ignoringFieldsMatchingRegexes(String…​ regexes)

Nested fields can be specified like this: home.address.street

It is also possible to ignore the the object under test with ignoringActualNullFields().

Examples

Person sherlock = new Person("Sherlock", 1.80);
sherlock.home.address.street = "Baker Street";
sherlock.home.address.number = 221;

// strangely moriarty and sherlock have the same height!
Person moriarty = new Person("Moriarty", 1.80);
moriarty.home.address.street = "Crime Street";
moriarty.home.address.number = 221;

// assertion succeeds as name and home.address.street fields are ignored in the comparison
assertThat(sherlock).usingRecursiveComparison()
                    .ignoringFields("name", "home.address.street")
                    .isEqualTo(moriarty);

// assertion succeeds as once a field is ignored, its subfields are too
assertThat(sherlock).usingRecursiveComparison()
                    .ignoringFields("name", "home")
                    .isEqualTo(moriarty);

// ignoring with regexes: name and home match .*me
assertThat(sherlock).usingRecursiveComparison()
                    .ignoringFieldsMatchingRegexes(".*me")
                    .isEqualTo(moriarty);

// ignoring null fields example:
sherlock.name = null;
sherlock.home.address.street = null;
assertThat(sherlock).usingRecursiveComparison()
                    .ignoringActualNullFields()
                    .isEqualTo(moriarty);

3.11.3. Ignoring overridden equals

By default the recursive comparison uses overridden equals methods to compare fields, it is possible to change that behavior and force a recursive comparison by calling:

  • ignoringOverriddenEqualsForTypes(Class…​) Any fields of these classes are compared recursively

  • ignoringOverriddenEqualsForFields(String…​) Any given fields are compared recursively

  • ignoringOverriddenEqualsForFieldsMatchingRegexes(String…​) Any fields matching one of these regexes are compared recursively

  • ignoringAllOverriddenEquals() except for java types, all fields are compared field by field recursively

Example:

public class Person {
  String name;
  double height;
  Home home = new Home();
}

public class Home {
  Address address = new Address();
}

public static class Address {
  int number;
  String street;

  // only compares number, ouch!
  @Override
  public boolean equals(final Object other) {
    if (!(other instanceof Address)) return false;
    Address castOther = (Address) other;
    return Objects.equals(number, castOther.number);
  }
}

Person sherlock = new Person("Sherlock", 1.80);
sherlock.home.address.street = "Baker Street";
sherlock.home.address.number = 221;

Person sherlock2 = new Person("Sherlock", 1.80);
sherlock2.home.address.street = "Butcher Street";
sherlock2.home.address.number = 221;

// assertion succeeds but that's not what we expected since the home.address.street fields differ
// but the equals implementation in Address does not compare them.
assertThat(sherlock).usingRecursiveComparison()
                    .isEqualTo(sherlock2);

// to avoid the previous issue, we force a recursive comparison on the Address type
// now this assertion fails as expected since the home.address.street fields differ.
assertThat(sherlock).usingRecursiveComparison()
                    .ignoringOverriddenEqualsForTypes(Address.class)
                    .isEqualTo(sherlock2);

3.12. Comparators used in the comparison

By default floats are compared with a precision of 1.0E-6 and doubles with 1.0E-15.

You can specify a custom comparator per (nested) fields or type with the methods below (but before calling isEqualTo otherwise this has no effect!):

  • withComparatorForFields(Comparator, String…​) for one or multiple fields

  • withComparatorForType(Comparator, Class) for a given type

Examples:

public class TolkienCharacter {
  String name;
  double height;
}

TolkienCharacter frodo = new TolkienCharacter("Frodo", 1.2);
TolkienCharacter tallerFrodo = new TolkienCharacter("Frodo", 1.3);
TolkienCharacter reallyTallFrodo = new TolkienCharacter("Frodo", 1.9);

Comparator<Double> closeEnough = (d1, d2) -> Math.abs(d1 - d2) <= 0.5 ? 0 : 1;

// assertion succeeds
assertThat(frodo).usingRecursiveComparison()
                 .withComparatorForFields(closeEnough, "height")
                 .isEqualTo(tallerFrodo);

assertThat(frodo).usingRecursiveComparison()
                 .withComparatorForType(closeEnough, Double.class)
                 .isEqualTo(tallerFrodo);


// assertions fail
assertThat(frodo).usingRecursiveComparison()
                 .withComparatorForFields(closeEnough, "height")
                 .isEqualTo(reallyTallFrodo);

assertThat(frodo).usingRecursiveComparison()
                 .withComparatorForType(closeEnough, Double.class)
                 .isEqualTo(reallyTallFrodo);

3.13. Soft assertions

With soft assertions AssertJ collects all assertion errors instead of stopping at the first one.

This is especially useful for long tests like end to end tests as we can fix all reported errors at once and avoid multiple failing runs.

Since soft assertions don’t fail at the first error, you need to tell AssertJ when to report the captured assertion errors, there are different ways of doing so:

Soft assertions comes with a BDD flavor where assertThat is replaced by then.

Let’s see first how to use soft assertions requiring an explicit call to assertAll(), the other approaches that don’t require this explicitit call are described in the subsequent sections.

Example:

@Test
void basic_soft_assertions_example() {
  SoftAssertions softly = new SoftAssertions(); (1)

  softly.assertThat("George Martin").as("great authors").isEqualTo("JRR Tolkien");  (2)
  softly.assertThat(42).as("response to Everything").isGreaterThan(100); (2)
  softly.assertThat("Gandalf").isEqualTo("Sauron"); (2)

  // Don't forget to call assertAll() otherwise no assertion errors are reported!
  softly.assertAll(); (3)
}
1 Build a SoftAssertions instance to record all assertion errors
2 Use softly.assertThat instead of the usual assertThat methods
3 Don’t forget to call assertAll() to report all assertion errors!

The previous test fails with the message below reporting all the errors:

Multiple Failures (3 failures)
-- failure 1 --
[great authors]
Expecting:
 <"George Martin">
to be equal to:
 <"JRR Tolkien">
but was not.
-- failure 2 --
[response to Everything]
Expecting:
 <42>
to be greater than:
 <100>
-- failure 3 --
Expecting:
 <"gandalf">
to be equal to:
 <"sauron">
but was not.

3.13.1. BDD Soft assertions

BDD aficionados can use BDD soft assertions where assertThat is replaced by then.

Example:

@Test
void basic_bdd_soft_assertions_example() {
  BDDSoftAssertions softly = new BDDSoftAssertions();

  softly.then("George Martin").as("great authors").isEqualTo("JRR Tolkien");
  softly.then(42).as("response to Everything").isGreaterThan(100);
  softly.then("Gandalf").isEqualTo("Sauron");

  // Don't forget to call assertAll() otherwise no assertion errors are reported!
  softly.assertAll();
}

There are BDD soft assertions versions for the different soft assertions approaches:

  • AutoCloseableBDDSoftAssertions

  • Using JUnitBDDSoftAssertions that takes care of calling assertAll() after each tests

  • Using a JUnit 5 extension that takes care of calling assertAll() after each tests

3.13.2. JUnit 4 Soft assertions rule

The JUnit rule provided by AssertJ takes care of calling assertAll() at the end of each tests.

Example:

@Rule
public final JUnitSoftAssertions softly = new JUnitSoftAssertions();

@Test
void junit4_soft_assertions_example() {
  softly.assertThat("George Martin").as("great authors").isEqualTo("JRR Tolkien");  (2)
  softly.assertThat(42).as("response to Everything").isGreaterThan(100); (2)
  softly.assertThat("Gandalf").isEqualTo("Sauron"); (2)
  // No need to call softly.assertAll(), this is automatically done by the JUnitSoftAssertions rule
}

In a similar way you can use JUnitBDDSoftAssertions where assertThat is replaced by then:

@Rule
public final JUnitBDDSoftAssertions softly = new JUnitBDDSoftAssertions();

@Test
void junit4_bdd_soft_assertions_example() {
  softly.then("George Martin").as("great authors").isEqualTo("JRR Tolkien");
  softly.then(42).as("response to Everything").isGreaterThan(100);
  softly.then("Gandalf").isEqualTo("Dauron");
  // No need to call softly.assertAll(), this is automatically done by the JUnitSoftAssertions rule
}

3.13.3. JUnit 5 Soft assertions extension

Since 3.13.0, AssertJ provides SoftAssertionsExtension a JUnit 5 extension that takes care of two things:

  • Injecting a SoftAssertions or BDDSoftAssertions parameter in each test methods

  • Calling assertAll() at the end of each tests

The term "test method" refers to any method annotated with @Test, @RepeatedTest, @ParameterizedTest, @TestFactory or @TestTemplate. Notably, the extension is compatible with parameterized tests, the parameterized arguments msut come first and the soft assertions argument last.

JUnitJupiterSoftAssertions and JUnitJupiterBDDSoftAssertions are now deprecated in favor of SoftAssertionsExtension

Example:

import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.api.extension.ExtendWith;
import org.assertj.core.api.BDDSoftAssertions;
import org.assertj.core.api.SoftAssertions;
import org.assertj.core.api.junit.jupiter.SoftAssertionsExtension;

@ExtendWith(SoftAssertionsExtension.class)
public class JUnit5SoftAssertionsExample {

  @Test
  void junit5_soft_assertions_multiple_failures_example(SoftAssertions softly) {
    softly.assertThat("George Martin").as("great authors").isEqualTo("JRR Tolkien");
    softly.assertThat(42).as("response to Everything").isGreaterThan(100);
    softly.assertThat("Gandalf").isEqualTo("Sauron");
    // No need to call softly.assertAll(), this is automatically done by the SoftAssertionsExtension
  }

  @Test
  void junit5_bdd_soft_assertions_multiple_failures_example(BDDSoftAssertions softly) {
    softly.then("George Martin").as("great authors").isEqualTo("JRR Tolkien");
    softly.then(42).as("response to Everything").isGreaterThan(100);
    softly.then("Gandalf").isEqualTo("Sauron");
    // No need to call softly.assertAll(), this is automatically done by the SoftAssertionsExtension
  }

  @ParameterizedTest
  @CsvSource({ "1, 1, 2", "1, 2, 3" })
  // test parameters come first, soft assertion must come last.
  void junit5_bdd_soft_assertions_parameterized_test_example(int a, int b, int sum, SoftAssertions softly) {
    softly.assertThat(a + b).as("sum").isEqualTo(sum);
    softly.assertThat(a).isLessThan(sum);
    softly.assertThat(b).isLessThan(sum);
  }

}

3.13.4. Auto Closeable Soft assertions

As AutoCloseableSoftAssertions implements AutoCloseable#close() by calling assertAll(), when used in a try-with-resources block assertAll() is called automatically before exiting the block.

Example:

@Test
void auto_closeable_soft_assertions_example() {
  try (AutoCloseableSoftAssertions softly = new AutoCloseableSoftAssertions()) {
  softly.assertThat("George Martin").as("great authors").isEqualTo("JRR Tolkien");  (2)
  softly.assertThat(42).as("response to Everything").isGreaterThan(100); (2)
  softly.assertThat("Gandalf").isEqualTo("Sauron"); (2)
    // no need to call assertAll, this is done when softly is closed.
  }
}

In a similar way you can use AutoCloseableBDDSoftAssertions where assertThat is replaced by then:

@Test
void auto_closeable_bdd_soft_assertions_example() {
  try (AutoCloseableBDDSoftAssertions softly = new AutoCloseableBDDSoftAssertions()) {
    softly.then("George Martin").as("great authors").isEqualTo("JRR Tolkien");
    softly.then(42).as("response to Everything").isGreaterThan(100);
    softly.then("Gandalf").isEqualTo("Sauron");
    // no need to call assertAll, this is done when softly is closed.
  }
}

3.13.5. Soft assertions with assertSoftly

The assertSoftly static method takes care of calling assertAll() before exiting.

Example:

@Test
void assertSoftly_example() {
  SoftAssertions.assertSoftly(softly -> {
    softly.assertThat("George Martin").as("great authors").isEqualTo("JRR Tolkien");
    softly.assertThat(42).as("response to Everything").isGreaterThan(100);
    softly.assertThat("Gandalf").isEqualTo("Sauron");
    // no need to call assertAll(), assertSoftly does it for us.
  });
}

3.14. Assumptions

Assumptions provide support for conditional test execution, if the assumptions are met the test is executed normally, if they don’t the test is aborted and marked as ignored.

Assumptions are typically used whenever it does not make sense to continue execution of a given test method — a typical usage is running tests depending on a given OS/environment.

All AssertJ assumptions are static methods in the Assumptions class, they match the assertion API but are names assumeThat insead of assertThat. You can also get assumptions through the WithAssumptions interface.

Example resulting in the test to be ignored:

@Test
public void when_an_assumption_is_not_met_the_test_is_ignored() {
  // since this assumption is obviously false ...
  assumeThat(frodo.getRace()).isEqualTo(ORC);
  // ... this assertion is not performed
  assertThat(fellowshipOfTheRing).contains(sauron);
}

Example resulting in the test to be executed normally:

@Test
public void when_all_assumptions_are_met_the_test_is_run_normally() {
  // since this assumption is true ...
  assumeThat(frodo.getRace()).isEqualTo(HOBBIT);
  // ... this assertion is performed
  assertThat(fellowshipOfTheRing).doesNotContain(sauron);
}

3.15. Javadoc

The latest version of assertj core javadoc is here:

4. Extending assertions

TODO

4.1. Conditions

TODO

4.2. Custom Assertions

TODO

5. Migrating assertions

This page will help you converting your existing JUnit assertions to AssertJ ones. Note that both types of assertions can coexist, you don’t have to migrate all at once.

The idea is to convert code like :

assertEquals(expected, actual);

to:

assertThat(actual).isEqualTo(expected);

There are several ways to perform the conversion :

The preferred way is using the scripts as it is quicker and covers more assertions that the other ones.

5.1. Assertions migration scripts

It is as simple as running one of the following script depending on which test framework you are using:

Each shell scripts is based on the sed stream editor and regexps. It recursively looks at all *Test.java files and performs search and replace to convert assertions to AssertJ ones.

The script handles the cases where you use an assertion description, for example:

assertEquals("test context", "a", "a");

will be replaced by:

assertThat("a").as("test context").isEqualTo("a");

Note that the script does a best effort and some assertions might not be converted if formatted on multiple lines. Anyway the script usually migrates the vast majority of assertions.

The script works on windows within a bash console like git bash (tested a long time ago) or cygwin (not tested).

5.1.1. Usage

Execute the script in the base directory containing the test files:

cd ./src/test/java
./convert-junit-assertions-to-assertj.sh

If the *Test.java file pattern does not suit you, just specify another as an argument:

# enclose your pattern with double quotes "" to avoid it to be expanded by your shell prematurely
./convert-junit-assertions-to-assertj.sh "*IT.java"

After executing it, you will need to :

  • Optimize imports with your IDE to remove unused imports.

  • If you were using assertEquals with a delta to compare numbers, you will need to statically import org.assertj.core.api.Assertions.within which is how you express deltas in AssertJ (see the number_assertions_with_offset_examples() test at the end of NumberAssertionsExamples).

5.1.2. Script output

Converting JUnit assertions to AssertJ assertions on files matching pattern : *Test.java

 1 - Replacing : assertEquals(0, myList.size()) ............... by : assertThat(myList).isEmpty()
 2 - Replacing : assertEquals(expectedSize, myList.size()) .... by : assertThat(myList).hasSize(expectedSize)
 3 - Replacing : assertEquals(expectedDouble, actual, delta) .. by : assertThat(actual).isCloseTo(expectedDouble, within(delta))
 4 - Replacing : assertEquals(expected, actual) ............... by : assertThat(actual).isEqualTo(expected)
 5 - Replacing : assertArrayEquals(expectedArray, actual) ..... by : assertThat(actual).isEqualTo(expectedArray)
 6 - Replacing : assertNull(actual) ........................... by : assertThat(actual).isNull()
 7 - Replacing : assertNotNull(actual) ........................ by : assertThat(actual).isNotNull()
 8 - Replacing : assertTrue(logicalCondition) ................. by : assertThat(logicalCondition).isTrue()
 9 - Replacing : assertFalse(logicalCondition) ................ by : assertThat(logicalCondition).isFalse()
10 - Replacing : assertSame(expected, actual) ................. by : assertThat(actual).isSameAs(expected)
11 - Replacing : assertNotSame(expected, actual) .............. by : assertThat(actual).isNotSameAs(expected)

Replacing JUnit static imports by AssertJ ones, at this point you will probably need to :
12 --- optimize imports with your IDE to remove unused imports
12 --- add "import static org.assertj.core.api.Assertions.within;" if you were using JUnit number assertions with deltas

5.2. Assertions migration regexes

Here’s a list of find/replace expressions to change JUnit assertions into AssertJ assertions (don’t forget to check the regex mode in your editor replace window).

This regexes described in this section are specfic to JUnit 4 but you can easily adapt them for JUnit 5 or TestNG.

The order of find/replace is important to benefit from the most relevant AssertJ assertions. For example you should convert assertEquals(0, myList.size()) to assertThat(myList).isEmpty() instead of assertThat(myList.size()).isEqualTo(0).

5.2.1. Converting assertEquals(0, myList.size()) to assertThat(myList).isEmpty()

Find/replace regex:

assertEquals\(0,(.*).size\(\)\); -> assertThat(\1).isEmpty();

It’s better to run this before the assertEqualsisEqualTo conversion to avoid ending with assertThat(myList.size()).isEqualTo(0).

5.2.2. Converting assertEquals(size, myList.size()) to assertThat(myList).hasSize(size)

Find/replace regex:

assertEquals\((.*),(.*).size\(\)\); -> assertThat(\2).hasSize(\1);

It’s better to run this before the assertEqualsisEqualTo conversion to avoid ending with assertThat(myList.size()).isEqualTo(expectedSize).

5.2.3. Converting assertEquals(expected, actual) to assertThat(actual).isEqualTo(expected)

Find/replace regex:

assertEquals\((.*),(.*)\); -> assertThat(\2).isEqualTo(\1);

5.2.4. Converting assertNull(objectUnderTest) to assertThat(objectUnderTest).isNull()

Find/replace regex:

assertNull\((.*)\); -> assertThat(\1).isNull();

5.2.5. Converting assertNotNull(objectUnderTest) to assertThat(objectUnderTest).isNotNull()

Find/replace regex:

assertNotNull\((.*)\); -> assertThat(\1).isNotNull();

5.2.6. Converting assertFalse(logicalCondition) to assertThat(logicalCondition).isFalse()

Find/replace regex:

assertFalse\((.*)\); -> assertThat(\1).isFalse();

6. AssertJ Sample Projects

The assertions-examples repository hosts executable AssertJ assertions examples that you can run as JUnit tests. Please have a look at assertions examples sources.

The master branch contains examples with the latest released version of AssertJ modules for Java 8, similarly the java-7 branch contains examples of AssertJ modules for Java 7. You should be able to build those two branches with mvn clean install command.

In your IDE, add src/test/generated-assertions to the project java test sources otherwise you will have errors/missing classes. This is the folder where custom assertions classes are generated by default by the maven assertions generator plugin. Note that Intellij Idea wrongly adds src/test/generated-assertions to the production sources when it should be added the test sources, you will have to fix that in your module/project settings.

Building the with-latest-snapshot-versions branch is a bit more complicated :

  • you need to build the needed SNAPSHOT dependencies before - most probably assertj-core and maybe other modules.

  • run mvn clean install in assertj-examples/assertions-examples.

  • In your IDE, add src/test/generated-assertions to the project java sources if you IDE shows errors/missing classes.

7. Contributors

Browse the current list of contributors directly on GitHub.

8. Release Notes

8.1. AssertJ Core

8.1.1. AssertJ Core 3.12.2 Release notes

The main issue fixed was to ignore static methods when finding property accessors (contributed by Andy Wilkinson) which could break some tests since bare name method introspection was introduced in 3.12.0.

anySatisfy for Maps was improved and does not continue evaluating elements once a match is found (contributed by Erhard Pointl).

8.1.2. AssertJ Core 3.12.1 Release notes

Fix a regression that included a bad module-info.class (thanks Jaro Kuruc) and other minor improvements.

8.1.3. AssertJ Core 3.12.0 Release notes

Release date : 2019-02-14

The main feature of this release is a beta version of the new Recursive comparison API! It covers what isEqualToComparingFieldByFieldRecursively used but easier to use and with more capabilities.

It is a Beta version because we want to have feedback from the community to make it even better before freezing the API. There are more capabilities to come in the next releases, stay tuned!

Contributors

Big thanks for all the contributors to this release:

Pascal Schumacher, Erhard Pointl, Vladimir Chernikov, Sandra Parsick, Martin Tarjanyi, Stephan Windmüller, Yaroslav Mitsynskiy, Thomas Traude, Georg Berky, Tomek Kaczanowski, Lukáš Křečan, Yoann Rodière, Filip Hrisafov, Steven Schlansker, Jeremy Landis, Jack Gough, Sebastian Kempken, Stefan Mandel, Alexandre de Champeaux, Arvid Heise, Jeff Walker, Dmitrii Priporov and Joshua Kitchen.

Breaking changes
  • Introduce first class Iterator assertions (Stephan Windmüller).

This removes the previously supported “Iterable” assertions (like containsOnly), call IteratorAssert#toIterable to access them again, ex:
Iterator<String> bestBasketBallPlayers = getBestBasketBallPlayers();

assertThat(bestBasketBallPlayers).toIterable().contains("Jordan", "Magic", "Lebron");
  • Add configurable support for bare-named property introspection. (Steven Schlansker)

AssertJ uses introspection in various places, one example is extracting properties as in extracting("name"). AssertJ is able to get values with getters like getName(), with this improvement it now can get property values with bare name method like name().

Bare-named property introspection is enabled by default and thus changes AssertJ behavior which can break some existing tests relying on introspection, this is especially true as AssertJ wrongly tries static methods (https://github.com/joel-costigliola/assertj-core/issues/1458 had been created to address that).

It is possible to avoid this probem by calling Assertions.setExtractBareNamePropertyMethods(false); before every impacted tests.

This is a bit tedious but an improvement is planned in the next release to provide a place to perform global configuration with the same mechanism allowing to register a custom representation.

New features
  • New Recursive comparison API! (Beta version)

  • Add satisfiesAnyOf base assertion. TODO document

  • Add isAbstract to Class assertions. (Erhard Pointl)

  • Add hasValueCloseTo(percentage) to OptionalDouble assertion. (Joshua Kitchen)

  • Add hasOnlyOneElementSatisfying(Consumer) to AtomicReferenceArray assertions. (Vladimir Chernikov)

  • Add hasAllNullFieldsOrProperties and hasAllNullFieldsOrPropertiesExcept. (Vladimir Chernikov)

  • Add hasSizeGreaterThan, hasSizeLessThanOrEqualTo, hasSizeGreaterThanOrEqualTo and hasSizeGreaterThan to CharSequence and String assertions. (Sandra Parsick)

  • Add hasSizeGreaterThan, hasSizeLessThanOrEqualTo, hasSizeGreaterThanOrEqualTo, hasSizeGreaterThan and hasSizeBetween to object and primitives array, Iterable and Map. (Martin Tarjanyi)

  • Add hasSizeBetween to CharSequence and String assertions. (Martin Tarjanyi)

  • Add noneSatisfy(BiConsumer) to Map assertions. (Erhard Pointl)

  • Add containsExactlyEntriesOf assertion to check that a Map contains exactly all entries of another Map. (Filip Hrisafov)

  • Add containsOnlyKeys(Iterable keys) to Map assertion. (Sebastian Kempken)

  • Add anySatifies(BiConsumer) to Map assertion. (Stefan Mandel)

  • Add hasMessageNotContaining to Throwable assertions. (Georg Berky and Sandra Parsick)

  • Add shouldHaveRootCause to Throwable assertions to check the content of a root cause. (Jack Gough)

  • Add isEqualTo(String string, Objects…​ param) to String assertion. (Dmitrii Priporov)

  • Add assertThatObject/thenObject to force Object assertion. (Arvid Heise)

  • Add JUnit5 to AssertJ assertions migration script for osx. (Tomek Kaczanowski)

Improvements
  • Add stack trace of original exception to catchThrowableOfType. (Sam Smyth)

  • anySatisfy and noneSatisfy now reports all failing elements. (Erhard Pointl)

  • ElementsShouldSatisfy now uses the configured Representation to format objects.

  • ZipSatisfyError now uses the configured Representation to format objects. (Jeff Walker)

  • AssertJ Double and Float comparators now support Infinity. (Alexandre de Champeaux)

  • Throw AssertionFailedError instead of AssertionError in some String assertions to allow IDEs to show actual vs expected visual differences. (Yaroslav Mitsynskiy)

  • Optional hasValue/contains assertions throws AssertionFailedError to allow IDEs to show actual vs expected visual differences.

  • Annotate Assertions and Assumptions classes with @CheckReturnValue and annotate methods to exclude from checking with @CanIgnoreReturnValue. (Pascal Schumacher)

  • The error message of allSatisfy(BiConsumer) Map assertion now reports all failing entries instead of the first one. (Stefan Mandel)

  • Add missing @Since annotations. (Erhard Pointl)

  • Get rid of Arguments usage when possible in unit tests. (Erhard Pointl)

  • Unit tests code cleanup and better use of JUnit 5. (Erhard Pointl, Pascal Schumacher and Jack Gough)

  • Update to JUnit 5.4.0. (Erhard Pointl)

  • Update to opentest4j to 1.1.1. (Erhard Pointl)

  • Update to Byte Buddy 1.9.10. (Pascal Schumacher)

  • Update Maven version to and the Maven wrapper. (Thomas Traude, Jeremy Landis)

  • Do not proxy useComparator method in soft assertions. (Lukáš Křečan)

  • Fix an NPE in ObjectArrays#assertHasOnlyElementsOfType. (Yoann Rodière)

  • Deprecate Extractor in favor of java.util.function.Function. (Filip Hrisafov)

Fixed
  • Use @CanIgnoreReturnValue on Assertions fail* methods to revert the effect of the default @CheckReturnValue annotation. (Erhard Pointl)

  • Fix ElementsShouldSatisfy that failed to handle objects whose string representation contained %.

  • Fix ElementsShouldZipSatisfy that failed to handle objects whose string representation contained %. (Arvid Heise)