This is now the official site for AssertJ Core replacing:

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 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.

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 3.x requires Java 8 or higher (use the org.assertj.core.api.Java6Assertions entry point on Android API Level < 26)

  • AssertJ 2.x requires Java 7 or higher (use the org.assertj.core.api.Java6Assertions entry point on Android API Level < 26)

  • AssertJ 1.x requires Java 6 or higher

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

2.1.2. Maven

  <!-- use 2.9.1 for Java 7 projects -->

2.1.3. Gradle

For Gradle users (using the Maven Central Repository)


Or version 2.9.1 for Java 7 projects


2.1.4. 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; // 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 {

  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







Future / CompletableFuture


Iterable (including any kind of Collection)






  • Optional

  • OptionalInt / OptionalLong / OptionalDouble





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







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())

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)

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!


// DON'T DO THIS ! It does not assert anything



// OR THIS (less classy but ok):


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


// DO THIS: (fails as expected)

// 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().


// DON'T DO THIS ! as/describedAs have no effect after the assertion


// DO THIS: use as/describedAs before the assertion

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().


// 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");


// 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().


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


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
  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
  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 overridding 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 ...

…​with the following error:

to start with:

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)


3.7. Common assertions

This section describes the assertions common to all types.

3.8. Object assertions


3.9. Iterable/Collection assertions


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 which heavily uses lambdas.

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 :

public void bdd_exception_assertion_example() {
   // GIVEN
   String[] names = { "Pier ", "Pol", "Jak" };
   // WHEN
   Throwable thrown = catchThrowable(() -> System.out.println(names[9]));
   // THEN
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) {
     this.line = line;
     this.column = column;

 TextException textException = catchThrowableOfType(() -> { throw new TextException("boom!", 1, 5); },
 // assertions succeed

 // 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 :

public void exception_assertion_example() {
   assertThatThrownBy(() -> { throw new Exception("boom!"); }).isInstanceOf(Exception.class)
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.

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

This later syntax has been enriched for common exceptions :

  • assertThatNullPointerException

  • assertThatIllegalArgumentException

  • assertThatIllegalStateException

  • assertThatIOException

The previous test can be rewritten as:

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

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

assertThatCode(() -> {
  // code that should NOT throw an exception

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.


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;
import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown;
// ... code omitted for brevety


// 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"
} 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.

// assertion fails as Person equals only compares references.

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

// 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

// 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.

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().


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
                    .ignoringFields("name", "home.address.street")

// assertion succeeds as once a field is ignored, its subfields are too
                    .ignoringFields("name", "home")

// ignoring with regexes: name and home match .*me

// ignoring null fields example: = null;
sherlock.home.address.street = null;

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


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!
  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 implemenation in Address does not compare them.

// 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.

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


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
                 .withComparatorForFields(closeEnough, "height")

                 .withComparatorForType(closeEnough, Double.class)

// assertions fail
                 .withComparatorForFields(closeEnough, "height")

                 .withComparatorForType(closeEnough, Double.class)

3.13. Soft Assertions


3.14. Assumptions

All AssertJ assumptions are static methods in the Assumptions class.


3.15. Javadoc

The latest version of assertj core javadoc is here:

4. Extending assertions


4.1. Conditions


4.2. Custom Assertions


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);



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 * 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

If the * 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
./ "*"

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 : *

 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!


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 ( 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)

  • 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)

  • 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)