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 Core?

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.

Here are a few examples of AssertJ assertions:

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

// basic assertions
assertThat(frodo.getName()).isEqualTo("Frodo");
assertThat(frodo).isNotEqualTo(sauron);

// chaining string specific assertions
assertThat(frodo.getName()).startsWith("Fro")
                           .endsWith("do")
                           .isEqualToIgnoringCase("frodo");

// collection specific assertions (there are plenty more)
// in the examples below fellowshipOfTheRing is a List<TolkienCharacter>
assertThat(fellowshipOfTheRing).hasSize(9)
                               .contains(frodo, sam)
                               .doesNotContain(sauron);

// as() is used to describe the test and will be shown before the error message
assertThat(frodo.getAge()).as("check %s's age", frodo.getName()).isEqualTo(33);

// exception assertion, standard style ...
assertThatThrownBy(() -> { throw new Exception("boom!"); }).hasMessage("boom!");
// ... or BDD style
Throwable thrown = catchThrowable(() -> { throw new Exception("boom!"); });
assertThat(thrown).hasMessageContaining("boom");

// using the 'extracting' feature to check fellowshipOfTheRing character's names
assertThat(fellowshipOfTheRing).extracting(TolkienCharacter::getName)
                               .doesNotContain("Sauron", "Elrond");

// extracting multiple values at once grouped in tuples
assertThat(fellowshipOfTheRing).extracting("name", "age", "race.name")
                               .contains(tuple("Boromir", 37, "Man"),
                                         tuple("Sam", 38, "Hobbit"),
                                         tuple("Legolas", 1000, "Elf"));

// filtering a collection before asserting
assertThat(fellowshipOfTheRing).filteredOn(character -> character.getName().contains("o"))
                               .containsOnly(aragorn, frodo, legolas, boromir);

// combining filtering and extraction (yes we can)
assertThat(fellowshipOfTheRing).filteredOn(character -> character.getName().contains("o"))
                               .containsOnly(aragorn, frodo, legolas, boromir)
                               .extracting(character -> character.getRace().getName())
                               .contains("Hobbit", "Elf", "Man");

// and many more assertions: iterable, stream, array, map, dates, path, file, numbers, predicate, optional ...

1.2. Getting Help

Ask AssertJ related questions on Stack Overflow.

1.3. Contributing to this guide

You are very welcome to suggest or contribute improvements to this guide, that’s one great way to give back to open source projects!

The repository containing the guide is https://github.com/assertj/doc, you can create a new issue, submit a pull request. Et voila!

This guide is written with the awesome asciidoctor which makes it easy to improve.

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 officially 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.14.0</version>
  <scope>test</scope>
</dependency>

2.1.4. Gradle

For Gradle users (using the Maven Central Repository)

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

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 entry point

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

2.2.1. Alternative entry points

AssertJ provides other entry points class, notably the WithAssertions interface and BDDAssertions for BDD style assertions that replace assertThat by then.

WithAssertions example:

import org.assertj.core.api.WithAssertions;

public class WithAssertionsExamples extends AbstractAssertionsExamples implements WithAssertions {

  // the data used are initialized in AbstractAssertionsExamples.

  @Test
  public void withAssertions_examples() {

    // assertThat methods come from WithAssertions - no static import needed
    assertThat(frodo.age).isEqualTo(33);
    assertThat(frodo.getName()).isEqualTo("Frodo").isNotEqualTo("Frodon");

    assertThat(frodo).isIn(fellowshipOfTheRing);
    assertThat(frodo).isIn(sam, frodo, pippin);
    assertThat(sauron).isNotIn(fellowshipOfTheRing);

    assertThat(frodo).matches(p -> p.age > 30 && p.getRace() == HOBBIT);
    assertThat(frodo.age).matches(p -> p > 30);
  }
}

BDDAssertions example:

import static org.assertj.core.api.BDDAssertions.then;

public class BDDAssertionsExamples extends AbstractAssertionsExamples {

  // the data used are initialized in AbstractAssertionsExamples.

  @Test
  public void withAssertions_examples() {

    // then methods come from BDDAssertions.then static
    then(frodo.age).isEqualTo(33);
    then(frodo.getName()).isEqualTo("Frodo").isNotEqualTo("Frodon");

    then(frodo).isIn(fellowshipOfTheRing);
    then(frodo).isIn(sam, frodo, pippin);
    then(sauron).isNotIn(fellowshipOfTheRing);

    then(frodo).matches(p -> p.age > 30 && p.getRace() == HOBBIT);
    then(frodo.age).matches(p -> p > 30);
  }
}

2.2.2. IDE configuration

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

Eclipse: . Go to : Window > Preferences > Java > Editor > Content Assist > Favorites > New Type . Enter : org.assertj.core.api.Assertions and click OK . Check that you see org.assertj.core.api.Assertions.* in Favorites.

Intellij Idea: 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. Configuring AssertJ

This section describes the different ways to configure AssertJ, either by setting configuration properties individually or globally using the Configuration class.

To be effective the configuration changes must be applied before the tests are executed, depending on the scope of the tests this means different things:

  • For a single test: change the configuration in the test and revert it in the @AfterEach method (JUnit 5).

  • For all tests in a class: change the configuration in the @BeforeAll method and revert the changes in the @AfterAll method (JUnit 5).

  • To change the configuration before any tests, you can use these options:

3.6.1. Configuring single properties

The Assertions class provides static methods to change each configuration properties.

Assertions.setAllowComparingPrivateFields(true);
Assertions.setAllowExtractingPrivateFields(false);
Assertions.setExtractBareNamePropertyMethods(false);
Assertions.setLenientDateParsing(true);
Assertions.setMaxElementsForPrinting(100);
Assertions.setMaxLengthForSingleLineDescription(250);
Assertions.setRemoveAssertJRelatedElementsFromStackTrace(true);
Assertions.useRepresentation(myRepresentation);
Assertions.registerCustomDateFormat(myCustomDateFormat);
Representation

This property allows you to register a Representation to control the way AssertJ formats the different types displayed in the assertion error messages. Consult the Controlling type formatting chapter for details.

Defaults to StandardRepresentation.

AllowComparingPrivateFields

Globally sets whether the use of private fields is allowed for field/property by field/property comparison. Defaults to true.

AllowExtractingPrivateFields

Globally sets whether the AssertJ extracting capability should be allowed to extract private fields. Defaults to true.

ExtractBareNamePropertyMethods

Globally sets whether the AssertJ extracting capability considers bare-named property methods like String name(). Defaults to true.

LenientDateParsing

Specify whether or not date/time parsing is to be lenient for AssertJ default date formats. With lenient parsing, the parser may use heuristics to interpret inputs that do not precisely match this object’s format. With strict parsing, inputs must match this object’s format.

Custom DateFormat

In addition to the default date formats, you can register some custom ones that AssertJ will use in date assertions (see also Assertions.registerCustomDateFormat).

Note that custom date formats take precedence over default ones.

MaxElementsForPrinting

In error messages, sets the threshold for how many elements from one iterable/array/map will be included in the in the description. Defaults to 1000.

The point of this property is to avoid printing iterable/array/map with too many elements in error messages.

MaxLengthForSingleLineDescription

In error messages, sets the threshold when iterable/array formatting will be on one line (if their String description is less than this parameter) or it will be formatted with one element per line. Defaults to 80.

Example:

String[] greatBooks = array("A Game of Thrones", "The Lord of the Rings", "Assassin's Apprentice");

this array is formatted on one line as its length < 80:

["A Game of Thrones", "The Lord of the Rings", "Assassin's Apprentice"]

Whereas this array …​

String[] greatBooks = array("A Game of Thrones", "The Lord of the Rings", "Assassin's Apprentice", "Guards! Guards! (Discworld)");

... is formatted on multiple lines with one element per line:

["A Game of Thrones",
 "The Lord of the Rings",
 "Assassin's Apprentice",
 "Guards! Guards! (Discworld)"]
RemoveAssertJRelatedElementsFromStackTrace

Sets whether the elements related to AssertJ are removed from assertion errors stack trace. Defaults to true.

3.6.2. AssertJ Configuration

Since 3.13.0, AssertJ exposes a org.assertj.core.configuration.Configuration object providing access to all AssertJ globally configurable properties.

You can create an instance of org.assertj.core.configuration.Configuration and change indivual properties through setters or create your own custom configuration by inheriting from it and overriding the methods to change the default behavior as in the CustomConfiguration example below.

Your configuration will be effective once you call Configuration.apply() or Configuration.applyAndDisplay().

Example:

Configuration configuration = new Configuration();

configuration.setBareNamePropertyExtraction(false);
configuration.setComparingPrivateFields(false);
configuration.setExtractingPrivateFields(false);
configuration.setLenientDateParsing(true);
configuration.setMaxElementsForPrinting(1001);
configuration.setMaxLengthForSingleLineDescription(81);
configuration.setRemoveAssertJRelatedElementsFromStackTrace(false);

// don't forget to apply it!
configuration.applyAndDisplay();

Printing the above configuration produces the following output:

Applying configuration org.assertj.core.configuration.Configuration
- representation .................................. = BinaryRepresentation
- comparingPrivateFieldsEnabled ................... = false
- extractingPrivateFieldsEnabled .................. = true
- bareNamePropertyExtractionEnabled ............... = false
- lenientDateParsingEnabled ....................... = true
- additionnal date formats ........................ = [yyyy_MM_dd, yyyy|MM|dd]
- maxLengthForSingleLineDescription ............... = 150
- maxElementsForPrinting .......................... = 2000
- removeAssertJRelatedElementsFromStackTraceEnabled = true

3.6.3. Automagic configuration discovery

This section describes a way to register an AssertJ Configuration without using any test framework hooks like BeforeAllCallback.

Follow the steps below to register your Configuration as an SPI:

  • Create your own configuration inheriting from org.assertj.core.configuration.Configuration

  • Create a file named org.assertj.core.configuration.Configuration in a META-INF/services directory

  • Make sure META-INF/services/ is in the runtime classpath, usually putting it in src/test/resources will do.

  • Put the fully qualified class name of your Configuration in services/org.assertj.core.configuration.Configuration.

This is all you have to do, AssertJ will pick up the Configuration automatically and display it at the first interaction with AssertJ.

Here’s an example of a custom configuration class:

package example.core;

import static org.assertj.core.presentation.BinaryRepresentation.BINARY_REPRESENTATION;
import static org.assertj.core.util.Lists.list;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;

import org.assertj.core.configuration.Configuration;
import org.assertj.core.presentation.Representation;

class CustomConfiguration extends Configuration {

  private static final SimpleDateFormat DATE_FORMAT1 = new SimpleDateFormat("yyyy_MM_dd");
  private static final SimpleDateFormat DATE_FORMAT2 = new SimpleDateFormat("yyyy|MM|dd");

  // we keep the default behavior for extractingPrivateFieldsEnabled since it is not overridden

  @Override
  public Representation representation() {
    return BINARY_REPRESENTATION;
  }

  @Override
  public boolean bareNamePropertyExtractionEnabled() {
    return false;
  }

  @Override
  public boolean comparingPrivateFieldsEnabled() {
    return false;
  }

  @Override
  public boolean lenientDateParsingEnabled() {
    return true;
  }

  @Override
  public List<DateFormat> additionalDateFormats() {
    return list(DATE_FORMAT1, DATE_FORMAT2);
  }

  @Override
  public int maxElementsForPrinting() {
    return 2000;
  }

  @Override
  public int maxLengthForSingleLineDescription() {
    return 150;
  }
}

With this custom configuration, the content of META-INF/services/org.assertj.core.configuration.Configuration must be:

example.core.CustomConfiguration

Printing the CustomConfiguration shows:

Applying configuration example.core.CustomConfiguration
- representation .................................. = BinaryRepresentation
- comparingPrivateFieldsEnabled ................... = false
- extractingPrivateFieldsEnabled .................. = true
- bareNamePropertyExtractionEnabled ............... = false
- lenientDateParsingEnabled ....................... = true
- additionnal date formats ........................ = [yyyy_MM_dd, yyyy|MM|dd]
- maxLengthForSingleLineDescription ............... = 150
- maxElementsForPrinting .......................... = 2000
- removeAssertJRelatedElementsFromStackTraceEnabled = true

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

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

3.7.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.7.2. 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());

Consider writing a JUnit 5 extension implementing BeforeAllCallback to make sure the representation is set once for all before any test is executed.

3.7.3. 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.8. Common assertions

This section describes the assertions common to all types.

3.9. Object assertions (TODO)

TODO

3.10. Iterable/Collection assertions (TODO)

TODO

3.11. 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.11.1. With Java 8 (AssertJ 3.x)

Testing assertions in Java 8 is elegant, thanks to lambdas! 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 is 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 latter 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.11.2. Throwable reference assertions reference (TODO)

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.11.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.12. 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.12.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.12.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.12.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.13. 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.14. 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.14.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.14.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.14.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 must 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.14.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.14.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.15. 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 instead 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.16. Javadoc

The latest version of assertj core javadoc is here:

4. Extending assertions (TODO)

TODO

4.1. Conditions (TODO)

TODO

4.2. Custom Assertions (TODO)

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 specific 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. Release Notes

7.1. AssertJ Core

AssertJ Core would not exist without its contributors, you can find them all directly on GitHub.

Latest release notes:

7.1.1. AssertJ Core 3.14.0 Release notes

Release date : 2019-10-27

Contributors

Thanks to all the contributors of this release: Erhard Pointl, Stefano Cordio, Jonas Berlin, Thami Inaflas, Geoffrey Arthaud, Carter Kozak, Kevin Toublanc, Krishna Chaithanya Ganta,sowmiyamuthuraman, Edgar Asatryan, Oleksii Khomchenko, Gonzalo Müller Bravo, Stephen O’Rourke, Sven Johansson, William Bakker, Rob Spieldenner, Raymond Pressly, Michael Keppler and Clemens Grabmann.

Breaking changes

  • Stop throwing an IllegalArgumentException when isIn and isNotIn are given an empty group of values.

New features

Improvements

  • AssertJ’s javadoc are now searchable.

  • Use beautiful AssertJ’s site code style for javadoc :)

  • ObjectAssert.extracting(String…​) learned to extract nested map key field/property. (Sven Johansson)

  • Prettify allOf and anyOf combined conditions description. (Edgar Asatryan)

  • Clearly differentiate top level objects in the new recursive comparison.

  • Show actual’s stack trace in hasRootCause and hasRootCauseMessage to give users more information. (Oleksii Khomchenko)

  • Show actual’s stack trace in hasMessageMatching and hasMessageFindingMatch to give users more information. (Stephen O’Rourke)

  • Update message text in ShouldHaveSameSizeAs to show both actual and expected collections. (Thami Inaflas)

  • Add matching syntactic sugar method to use Hamcrest Matcher as Condition. (Jonas Berlin)

  • Update ByteBuddy to version 1.10.2.

  • Fix javadoc typos and incorrect references. (Erhard Pointl, Stefano Cordio)

  • Stop throwing an IllegalArgumentException when isIn and isNotIn are given an empty group of values.

  • Expose AbstractAssert.objects to be used by subclasses.

  • Bump opentest4j from 1.1.1 to 1.2.0. (still optional)

  • Improve HamcrestCondition generic type inference. (Carter Kozak)

  • Remove shouldHaveThrown(Assertion.class) used internally. (sowmiyamuthuraman)

  • Replace catchThrowable + isInstanceOf(AssertionError.class) by expectAssertionError (internal use). (Clemens Grabmann)

  • Rewrite CompletableFutureAssert tests with assertThatAssertionErrorIsThrownBy. (internal use). (Clemens Grabmann)

Fixed

  • Fix BDDSoftAssertions.then(URL actual) that just did not work 🤦‍. (Rob Spieldenner)

  • Fix possible MissingFormatArgumentException in ShouldHaveMessage and ShouldContain. (Erhard Pointl)

  • Fix javadoc search.

  • Fix javadoc links. (Stefano Cordio)

  • Fix hasSizeBetween() that did not work with strings. (Geoffrey Arthaud)

  • Fix failing soft assertions when combined with asInstanceOf.

  • Fix missing soft assertions proxying for get of OptionalAssert. (Stefano Cordio)

  • Make convert-junit-assertions-to-assertj.sh conversion script work on Windows. (Michael Keppler)

Deprecated

  • Deprecate the confusing containsOnlyElementsOf in favor of isSubsetOf or hasSameElementsAs.

  • Deprecate Map assertions extracting(Object) and extracting(Object…​) in favor of extractingByKey(KEY) and extractingByKeys(KEY…​), respectively. (Stefano Cordio)

Add BDD assumptions

Add Behavior Driven Development style entry point for assumption methods for different types, which allow to skip test execution when assumptions are not met.

The difference with the Assumptions class is that entry point methods are named given instead of assumeThat.

Example:

String hobbit = "HOBBIT";
List<String> fellowshipOfTheRing = list("Aragorn", "Gandalf", "Frodo", "Legolas");

@Test
public void given_the_assumption_is_not_met_the_test_is_skipped() {
  given(hobbit).isEqualTo("ORC");
  // ... following code is not executed, the test is skipped
  then(fellowshipOfTheRing).contains("Sauron");
}

@Test
public void given_the_assumption_is_met_the_test_is_executed() {
  given(hobbit).isEqualTo("HOBBIT");
  // ... following code is executed and fails!
  then(fellowshipOfTheRing).doesNotContain("Sauron");
}

Add Spliterator assertions

Add hasCharacteristics and hasOnlyCharacteristics assertions for the Spliterator type.

Example:

Spliterator<Integer> spliterator = Stream.of(1, 2, 3).spliterator();

assertThat(spliterator).hasCharacteristics(Spliterator.SIZED,
                                           Spliterator.ORDERED)
                       .hasOnlyCharacteristics(Spliterator.SIZED,
                                               Spliterator.SUBSIZED,
                                               Spliterator.IMMUTABLE,
                                               Spliterator.ORDERED);

Add isAtSameInstantAs to OffsetDateTime assertions

Verifies that actual and given OffsetDateTime are at the same Instant.

Example:

OffsetDateTime offsetDateTime1 = OffsetDateTime.of(2000, 12, 12, 3, 0, 0, 0, ZoneOffset.ofHours(3));
OffsetDateTime offsetDateTime2 = OffsetDateTime.of(2000, 12, 12, 0, 0, 0, 0, ZoneOffset.ofHours(0));
// assertion succeeds
assertThat(offsetDateTime1).isAtSameInstantAs(offsetDateTime2);

offsetDateTime2 = OffsetDateTime.of(2000, 12, 12, 2, 0, 0, 0, ZoneOffset.ofHours(0));
// assertion fails
assertThat(offsetDateTime1).isAtSameInstantAs(offsetDateTime2);

Add assertAlso SoftAssertions method to allow combining different soft assertions instances

assertAlso lets you combine other soft assertions instances together.

Example:

public SoftAssertions check_kitchen() {
  SoftAssertions softly = new SoftAssertions();
  softly.assertThat(mansion.kitchen()).as("Kitchen").isEqualTo("clean");
  return softly;
}

public SoftAssertions check_library() {
  SoftAssertions softly = new SoftAssertions();
  softly.assertThat(mansion.library()).as("Library").isEqualTo("clean");
  return softly;
}

@Test
public void host_dinner_party_where_nobody_dies() {
  Mansion mansion = new Mansion();
  mansion.hostPotentiallyMurderousDinnerParty();
  softly.assertThat(mansion.guests()).as("Living Guests").isEqualTo(7);
  softly.assertThat(mansion.revolverAmmo()).as("Revolver Ammo").isEqualTo(6);
  softly.assertThat(mansion.candlestick()).as("Candlestick").isEqualTo("pristine");
  softly.assertThat(mansion.colonel()).as("Colonel").isEqualTo("well kempt");
  softly.assertThat(mansion.professor()).as("Professor").isEqualTo("well kempt");

  SoftAssertions kitchen = check_kitchen();
  softly.assertAlso(kitchen);

  SoftAssertions library = check_library();
  softly.assertAlso(library);

  softly.assertAll();
}

Add isEmpty and isNotEmpty file assertions

Verify that the actual File is empty (i.e. the file size = 0) or not empty (i.e. the file size > 0) .

Example:

File file = File.createTempFile("tmp", "txt");

// assertion will pass
assertThat(file).isEmpty();

Files.write(file.toPath(), new byte[]{1, 1});

// assertion will pass
assertThat(file).isNotEmpty();

Add hasSize(long expectedSizeInBytes) to File assertions

Verifies that the size of the File under test is exactly equal to the given size in bytes.

Example:

File file = File.createTempFile("tmp", "bin");
Files.write(file.toPath(), new byte[] {1, 1});

// assertion will pass
assertThat(file).hasSize(2);

// assertion will fail
assertThat(file).hasSize(1);

Avoid BDDMockito/BDDAssertions then(object) clash with and.then(object)

To avoid clash with libraries like Mockito that exposes a static then(object) method, you can statically use the and field.

import static org.mockito.BDDMockito.then;
// can't use import static org.assertj.core.api.BDDAssertions.then because of BDDMockito.then;
import static org.assertj.core.api.BDDAssertions.and;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;

// suppress and.then warning: The static method BDDAssertions.then() should be accessed in a static way
@SuppressWarnings("static-access")
@Test
public void bdd_assertions_with_bdd_mockito() {
  // GIVEN
  Person person = mock(Person.class)
  // WHEN
  person.ride(bike);
  person.ride(bike);
  // THEN
  // mockito then()
  then(person).should(times(2)).ride(bike);
  // use AssertJ and.then(person) as then(person) would clash with mockito then(person)
  and.then(person.hasBike()).isTrue();
}

Add hasRootCauseMessage to Throwable assertions

Verifies that the message of the root cause of the actual Throwable is equal to the given one, a simple String or String.format is supported to specify the expected root cause message.

Example:

Throwable throwable = new Throwable(new IllegalStateException(new NullPointerException("expected message")));

// assertions will pass
assertThat(throwable).hasRootCauseMessage("expected message")
                     .hasRootCauseMessage("expected %s", "message");

// assertions will fail
assertThat(throwable).hasRootCauseMessage("another message");
assertThat(throwable).hasRootCauseMessage("%s", "message");
// no root cause message
assertThat(new Throwable()).hasRootCauseMessage("%s %s", "expected", "message");

Add syntax sugar as(InstanceOfAssertFactory) to Assertions and WithAssertions for improved readability

A syntax sugar to write fluent assertion with methods having an InstanceOfAssertFactory parameter. Added as a static method in Assertions, it is also available as a default method in the WithAssertions interface.

Example:

Jedi yoda = new Jedi("Yoda", "Green");

assertThat(yoda).extracting(Jedi::getName, as(InstanceOfAssertFactories.STRING))
                .startsWith("Yo");

as(InstanceOfAssertFactory) can be used together with the following assertion methods:

Add extracting with String and InstanceOfAssertFactory parameters to Object assertions

Extracts the value of given field/property from the object under test, the extracted value becoming the new object under test. The InstanceOfAssertFactory parameter is used to get the assertions narrowed to the factory type.

Examples:

// Create frodo, setting its name, age and Race (Race having a name property)
TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT);

// let's extract and verify Frodo's name:
assertThat(frodo).extracting("name", as(InstanceOfAssertFactories.STRING))
                 .startsWith("Fro");

// The following assertion will fail as Frodo's name is not an Integer:
assertThat(frodo).extracting("name", as(InstanceOfAssertFactories.INTEGER))
                 .isZero();

Add extracting with Function and InstanceOfAssertFactory parameters to Object assertions

Uses the given Function to extract a value from the object under test, the extracted value becoming the new object under test. The InstanceOfAssertFactory parameter is used to get the assertions narrowed to the factory type.

Examples:

// Create frodo, setting its name, age and Race (Race having a name property)
TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT);

// let's extract and verify Frodo's name:
assertThat(frodo).extracting(TolkienCharacter::getName, as(InstanceOfAssertFactories.STRING))
                 .startsWith("Fro");

// The following assertion will fail as Frodo's name is not an Integer:
assertThat(frodo).extracting(TolkienCharacter::getName, as(InstanceOfAssertFactories.INTEGER))
                 .isZero();

Add extractingByKey with KEY and InstanceOfAssertFactory parameters to Map assertions

Extracts the value of given key from the map under test, the extracted value becoming the new object under test. The InstanceOfAssertFactory parameter is used to get the assertions narrowed to the factory type.

Examples:

Map<String, Object> map = new HashMap<>();
map.put("name", "kawhi");

// The following assertion will succeed:
assertThat(map).extractingByKey("name", as(InstanceOfAssertFactories.STRING))
               .startsWith("kaw");

// The following assertion will fail as the value is not an Integer:
assertThat(map).extractingByKey("name", as(InstanceOfAssertFactories.INTEGER))
               .isZero();

Add get with InstanceOfAssertFactory parameters to Optional assertions

Verifies that the optional is not null and not empty and returns an new assertion instance to chain assertions on the optional value. The InstanceOfAssertFactory parameter is used to get the assertions narrowed to the factory type.

Examples:

Optional<String> optional = Optional.of("Frodo");

// The following assertion will succeed:
assertThat(optional).get(as(InstanceOfAssertFactories.STRING))
                    .startsWith("Fro");

// The following assertion will fail as the value is not an Integer:
assertThat(optional).get(as(InstanceOfAssertFactories.INTEGER))
                    .isZero();

Add first with InstanceOfAssertFactory parameters to Iterable assertions

Navigates and allows to perform assertions on the first element of the Iterable under test. The InstanceOfAssertFactory parameter is used to get the assertions narrowed to the factory type.

Examples:

Iterable<String> hobbits = newArrayList("Frodo", "Sam", "Pippin");

// assertion succeeds
assertThat(hobbits).first(as(InstanceOfAssertFactories.STRING))
                   .startsWith("Fro")
                   .endsWith("do");
// assertion fails
assertThat(hobbits).first(as(InstanceOfAssertFactories.STRING))
                   .startsWith("Pip");
// assertion fails because of wrong factory type
assertThat(hobbits).first(as(InstanceOfAssertFactories.INTEGER))
                   .isZero();

Add last with InstanceOfAssertFactory parameters to Iterable assertions

Navigates and allows to perform assertions on the last element of the Iterable under test. The InstanceOfAssertFactory parameter is used to get the assertions narrowed to the factory type.

Examples:

Iterable<String> hobbits = newArrayList("Frodo", "Sam", "Pippin");

// assertion succeeds
assertThat(hobbits).last(as(InstanceOfAssertFactories.STRING))
                   .startsWith("Pip")
                   .endsWith("pin");
// assertion fails
assertThat(hobbits).last(as(InstanceOfAssertFactories.STRING))
                   .startsWith("Fro");
// assertion fails because of wrong factory type
assertThat(hobbits).last(as(InstanceOfAssertFactories.INTEGER))
                   .isZero();

Add element with InstanceOfAssertFactory parameters to Iterable assertions

Navigates and allows to perform assertions on the chosen element of the Iterable under test. The InstanceOfAssertFactory parameter is used to get the assertions narrowed to the factory type.

Examples:

Iterable<String> hobbits = newArrayList("Frodo", "Sam", "Pippin");

// assertion succeeds
assertThat(hobbits).element(1, as(InstanceOfAssertFactories.STRING))
                   .startsWith("Sa")
                   .endsWith("am");
// assertion fails
assertThat(hobbits).element(1, as(InstanceOfAssertFactories.STRING))
                   .startsWith("Fro");
// assertion fails because of wrong factory type
assertThat(hobbits).element(1, as(InstanceOfAssertFactories.INTEGER))
                   .isZero();

Add String.format support for expected message in hasMessageStartingWith, hasMessageContaining, hasMessageEndingWith and hasStackTraceContaining assertions

Instead of taking a simple String the assertions mentioned above now accept a String.format like parameters, i.e. (String description, Object…​ parameters) making it easier to build more involved expected strings.

Examples:

Throwable throwableWithMessage = new IllegalArgumentException("wrong amount 123");

assertThat(throwableWithMessage).hasMessageStartingWith("%s a", "wrong")
                                .hasMessageContaining("wrong %s", "amount")
                                .hasMessageEndingWith("%s 123", "amount")
                                .hasStackTraceContaining("%s amount", "wrong");

ObjectAssert.extracting(String…​) learned to extract nested map key field/property

extracting is now able to extract a deeply nested map key, before this improvement extracting a value by key was only supported for a Map object under test (but not for fields of type Map).

Let’s clarify things with a concrete example:

Jedi luke = new Jedi(new Name("Luke", "Skywalker"), 26);
// setAttribute puts a new entry in 'attributes' Map field
luke.setAttribute("side", "light");

Jedi leia = new Jedi(new Name("Leia", "Skywalker"), 26);
// setRelation puts a new entry in 'relations' Map field
luke.setRelation("sister", leia);
leia.setRelation("brother", luke);

assertThat(luke).extracting("name.last",
                            "attributes.side",
                            "relations.sister",
                            "relations.sister.relations.brother")
                .containsExactly("Skywalker",
                                 "light",
                                 leia,
                                 luke);

Prettify allOf and anyOf combined conditions description

To make it more readable, reformat the error message when multiple combined conditions with allOf and anyOf fail.

Examples: the following assertion will fail …​

private static Condition<String> contains(String s) {
  return new Condition<>(value -> value.contains(s), "contains " + s);
}

// failing assertion:
assertThat("Gandalf").has(anyOf(contains("i"),
                                allOf(contains("o"),
                                      anyOf(contains("a"),
                                            contains("b"),
                                            contains("c")))));

With the following error message

Expecting:
 <"Gandalf">
to have:
 <any of:[
   contains i,
   all of:[
      contains o,
      any of:[
         contains a,
         contains b,
         contains c
      ]
   ]
]>

Add matching syntactic sugar method to use Hamcrest Matcher as Condition

Syntactic sugar to construct a Condition using the Hamcrest Matcher given as a parameter.

Example:

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.HamcrestCondition.matching;
import static org.hamcrest.core.StringContains.containsString;

@Test
public void matching_example() {
 assertThat("abc").is(matching(containsString("a")));
}

7.1.2. AssertJ Core 3.13.2 Release notes

Release date : 2019-08-04

This release ships a few improvements:

  • Fixes an annoyance in InstanceOfAssertFactories, where URL and URI constants have been renamed to URL_TYPE and URI_TYPE respectively to avoid a clash with java.net.URL and java.net.URI. See https://github.com/joel-costigliola/assertj-core/issues/1567 for details.

  • Updates ByteBuddy to version 1.10.0.

  • Fixes some javadoc typos.

  • Enforces banned dependencies with maven-enforcer-plugin.

7.1.3. AssertJ Core 3.13.1 Release notes

Release date : 2019-07-29

This release addresses the 3.13.0 issue by which AssertJ required OpenTest4J to be on the classpath otherwise a java.lang.NoClassDefFoundError: org/opentest4j/MultipleFailuresError would be raised. Thanks Pascal Schumacher for the quick fix!

java.lang.NoClassDefFoundError: org/opentest4j/MultipleFailuresError
   at java.base/java.lang.ClassLoader.defineClass1(Native Method)
   at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1016)
   at java.base/java.security.SecureClassLoader.defineClass(SecureClassLoader.java:174)
   at java.base/jdk.internal.loader.BuiltinClassLoader.defineClass(BuiltinClassLoader.java:802)
   at java.base/jdk.internal.loader.BuiltinClassLoader.findClassOnClassPathOrNull(BuiltinClassLoader.java:700)
   at java.base/jdk.internal.loader.BuiltinClassLoader.loadClassOrNull(BuiltinClassLoader.java:623)
   at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
   at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
   at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
   at org.assertj.core.internal.Failures.<init>(Failures.java:46)
   at org.assertj.core.internal.Failures.<clinit>(Failures.java:44)
   at org.assertj.core.internal.Objects.<init>(Objects.java:87)
   at org.assertj.core.internal.Objects.<init>(Objects.java:101)
   at org.assertj.core.internal.Objects.<clinit>(Objects.java:82)
   at org.assertj.core.api.AbstractAssert.<init>(AbstractAssert.java:65)
   at org.assertj.core.api.AbstractCharSequenceAssert.<init>(AbstractCharSequenceAssert.java:53)
   at org.assertj.core.api.AbstractStringAssert.<init>(AbstractStringAssert.java:28)
   at org.assertj.core.api.StringAssert.<init>(StringAssert.java:25)
   at org.assertj.core.api.AssertionsForClassTypes.assertThat(AssertionsForClassTypes.java:484)
   at org.assertj.core.api.Assertions.assertThat(Assertions.java:2585)

7.1.4. AssertJ Core 3.13.0 Release notes

Release date : 2019-07-28

The highlight of this release is the addition of asInstanceOf which allows to chain specific type assertions from a value that was initially declared with a different type (usually Object). Thanks Stefano Cordio for this contribution!

Example:

Object value = "abc";

// This line DOES NOT COMPILE since startsWith is a String assertion and value is an Object
assertThat(value).startsWith("ab");

// This line COMPILES because we tell AssertJ to consider value as a String
assertThat(value).asInstanceOf(InstanceOfAssertFactories.STRING).startsWith("ab");

This feature is more detailed in the notes below.

Contributors

Thanks to all the contributors of this release:

Pascal Schumacher, Erhard Pointl, Stefano Cordio, Thomas Traude, Andrei Solntsev, Matej Drobnič, Željko Mirović, Mike Gilchrist, Phillip Webb, Michal Fotyga,Valeriy Vyrva, Eddú Meléndez Gonzales, GaspardPO, Bengt Brodersen, Jiri Pejchal, Christian Stein, Nikolaos Georgiou and Sam Brannen.

Special thanks to Nils Winkler for his work on the assertions conversion scripts and Stefano Cordio for the asInstanceOf contribution.

Breaking changes

  • As the extracting(String) method for Object and Map extracts only one value, it now returns Object assertions instead of list assertions (on a singleton list). This means that any list assertions used won’t compile anymore, they need to be replaced by Object assertions.

// GIVEN
Map<String, Object> basketballPlayer = new HashMap<>();
basketballPlayer.put("name", "kawhi");
basketballPlayer.put("age", 25);

// Does not compile anymore!
assertThat(basketballPlayer).extracting("name")
                            .containsExactly("kawhi"); // DOES NOT COMPILE

// Use Object assertions like isEqualTo
assertThat(basketballPlayer).extracting("name")
                            .isEqualTo("kawhi");

// multiple values work as before, no problem there!
assertThat(basketballPlayer).extracting("name", "age")
                            .containsExactly("kawhi", 25);
  • In the new recursive comparison, we now use the expected field as a reference to determine how to compare it to corresponding the actual field. Sorted vs non sorted collections comparison semantics have been replaced by ordered vs unordered collections semantics (ordered types are List, SortedSet and LinkedHashSet). As a consequence of the two previous points, when comparing collection/map fields, if the actual field is ordered and the expected is unordered, the comparison is allowed but not the other way around (unless order is ignored explicitely in the comparison configuration).

New features

Improvements

  • Junit 4/5 and TestNG assertions convertion scripts improvements. (Nils Winkler)

  • Add support for combined millisecond and timezone parsing. (Matej Drobnič)

  • Add support for Optional in the new recursive comparison.

  • Allow ignoring collection order in specific fields in the new recursive comparison. (Željko Mirović)

  • Make catchThrowableOfType easier to discover in the javadoc.

  • Rename methods isBeforeOrEqualsTo and isAfterOrEqualsTo to isBeforeOrEqualTo and isAfterOrEqualTo. (Eddú Meléndez Gonzales)

  • Improve error messages in the new recursive comparison when group size differs or when trying to compare actual unordered vs expected ordered.

  • Introduce explicit module descriptor. (Christian Stein)

  • Allow returned values of WithAssertions#fail methods to be ignored by findbugs/spotbugs. (Jiri Pejchal)

  • Improve the error message when multiple (soft) assertions error are raised.

  • Propagate value type with extracting(Function). (Stefano Cordio)

Fixed

  • Fix Soft assertions JUnit 5 extension that did not support parallel test nor @TestInstance(PER_CLASS) lifecycle semantics. (Sam Brannen)

  • Fix JavaDoc regarding AnyOf and AllOf. (Thomas Traude)

  • Make sure that isEqualTo("abc") is not resolved to isEqualTo(String, Object…​ args). (Andrei Solntsev)

  • Fix Javadoc typos. (GaspardPO, Michal Fotyga)

  • Fix typo in error message factories ShouldBeBeforeOrEqualTo and ShouldBeAfterOrEqualTo. (Stefano Cordio)

Deprecated

  • Deprecate Java 6/Android assertions entry points as they don’t truly provide 100% Java 6/Android compatibility.

  • Deprecate methods isBeforeOrEqualTo and isAfterOrEqualTo in favor of isBeforeOrEqualsTo and isAfterOrEqualsTo (Eddú Meléndez Gonzales).

  • Deprecate JUnitJupiterSoftAssertions and JUnitJupiterBDDSoftAssertions in favor of SoftAssertionsExtension

Add asInstanceOf to chain specific type assertions

asInstanceOf allows to chain specific type assertions from a value initially declared as a less specific type (often Object).

Let’s start with the problem asInstanceOf is solving: in the following example we would like to call String assertions but this is not possible since value is declared as an Object thus only Object assertions are accessible.

// Given a String declared as an Object
Object value = "Once upon a time in the west";

// We would like to call String assertions but this is not possible since value is declared as an Object
assertThat(value).startsWith("ab"); // this does not compile !

Thanks to asInstanceOf we can now tell AssertJ to consider value as a String in order to call String assertions. To do so we need to pass an InstanceOfAssertFactory that can build a StringAssert, fortunately you don’t have to write it, it is already available in InstanceOfAssertFactories!

import static org.assertj.core.api.InstanceOfAssertFactories.STRING;

// Given a String declared as an Object
Object value = "Once upon a time in the west";

// With asInstanceOf, we switch to specific String assertion by specifying the InstanceOfAssertFactory for String
assertThat(value).asInstanceOf(STRING).startsWith("Once");

AssertJ verifies that the actual value is compatible with the assertions InstanceOfAssertFactory is going to give access to.

InstanceOfAssertFactories provides static factories for all types AssertJ provides assertions for, additional factories can be created with custom InstanceOfAssertFactory instances.

Here’s another example showing the parameterized type support:

// Actually a List<TolkienCharacter>
Object hobbits = list(frodo, pippin, merry, sam);

// As we specify the TolkienCharacter class, the following chained assertion expect to be given TolkienCharacters.
// This means that method like extracting or filteredOn are given a TolkienCharacter
assertThat(hobbits).asInstanceOf(InstanceOfAssertFactories.list(TolkienCharacter.class))
                   .contains(frodo, sam)
                   .extracting(TolkienCharacter::getName)
                   .contains("Frodo", "Sam");

// Use LIST if the elements type is not important but note that the chained assertions
// will be given Object not TolkienCharacter
assertThat(hobbits).asInstanceOf(InstanceOfAssertFactories.LIST)
                    //.extracting(TolkienCharacter::getName) does not work as extracting is given an Object
                   .contains(frodo);

Add extracting with single parameter to Object and Map assertions

Extracts the value of given field/property from the object under test, the extracted value becoming the new object under test.

Examples:

// Create frodo, setting its name, age and Race (Race having a name property)
TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT);

// let's extract and verify Frodo's name:
assertThat(frodo).extracting("name")
                 .isEqualTo("Frodo");

// The extracted value being a String, we would like to use String assertions but we can't due to Java generics limitations.
// The following assertion does NOT compile:
assertThat(frodo).extracting("name")
                 .startsWith("Fro");

// To get String assertions use asInstanceOf:
assertThat(frodo).extracting("name")
                 .asInstanceOf(InstanceOfAssertFactories.STRING)
                 .startsWith("Fro");

If the object under test is a Map, the parameter is used as a key to the map.

Example:

Map<String, Object> basketballPlayer = new HashMap<>();
basketballPlayer.put("name", "kawhi");
basketballPlayer.put("age", 25);

// single value
assertThat(basketballPlayer).extracting("name")
                            .isEqualTo("kawhi");

AssertJ global configuration

AssertJ 3.13.0 introduces a Configuration class allowing to change AssertJ behavior and a way to register automatically. Read Configuring AssertJ chapter to learn about it.

Add hasCauseReference to throwable assertions

Verifies that the actual Throwable has a cause that refers to the given one, i.e. using == comparison.

Example:

Throwable invalidArgException = new IllegalArgumentException("invalid arg");
Throwable throwable = new Throwable(invalidArgException);

// This assertion succeeds:
assertThat(throwable).hasCauseReference(invalidArgException);

// These assertions fail:
assertThat(throwable).hasCauseReference(new IllegalArgumentException("invalid arg"));
assertThat(throwable).hasCauseReference(new NullPointerException());
assertThat(throwable).hasCauseReference(null); // prefer hasNoCause()

New directory content assertions

The new assertions have been added for both File and Path, they add support for

Both isDirectoryContaining and isDirectoryNotContaining accept either Predicate or String parameters, the String one being interpreted as a path matcher.

As File and Path assertions are similar, the examples will only show File assertions.

The examples use the following directory structure:

/root/
/root/sub-dir-1/
/root/sub-dir-1/file-1.ext
/root/sub-dir-1/file-2.ext
/root/sub-dir-2/
/root/sub-file-1.ext
/root/sub-file-2.ext

isDirectoryContaining assertions examples:

File root = new File("root");

// Successfull assertions with predicate parameter:
assertThat(root).isDirectoryContaining(file -> file.getName().startsWith("sub-dir"))
                .isDirectoryContaining(file -> file.getName().startsWith("sub-file"))
                .isDirectoryContaining(file -> file.getName().endsWith(".ext"))
                .isDirectoryContaining(File::isDirectory);

// Successfull assertions with String path matcher parameter:
assertThat(root).isDirectoryContaining("glob:**sub-dir*")
                .isDirectoryContaining("glob:**sub-file*")
                .isDirectoryContaining("glob:**.ext")
                .isDirectoryContaining("regex:.*ext")
                .isDirectoryContaining("glob:**.{ext,bin");


// The following assertions fail:
assertThat(root).isDirectoryContaining(file -> file.getName().startsWith("dir"));
assertThat(root).isDirectoryContaining(file -> file.getName().endsWith(".bin"));
assertThat(root).isDirectoryContaining("glob:**dir");
assertThat(root).isDirectoryContaining("glob:**.bin");

isDirectoryNotContaining assertion examples:

File root = new File("root");

// Successfull assertions with predicate parameter:
assertThat(root).isDirectoryNotContaining(file -> file.getName().startsWith("dir"))
                .isDirectoryNotContaining(file -> file.getName().endsWith(".bin"));

// Successfull assertions with String path matcher parameter:
assertThat(root).isDirectoryNotContaining("glob:**dir")
                .isDirectoryNotContaining("glob:**.bin")
                .isDirectoryNotContaining("regex:.*bin")
                .isDirectoryNotContaining("glob:**.{java,class}");

// The following assertions fail:
assertThat(root).isDirectoryContaining(file -> file.getName().startsWith("dir"));
assertThat(root).isDirectoryContaining(file -> file.getName().endsWith(".bin"));
assertThat(root).isDirectoryNotContaining("glob:**sub-dir*");
assertThat(root).isDirectoryNotContaining("regex:.*ext");
assertThat(root).isDirectoryNotContaining("glob:**.{ext,bin");

isEmptyDirectory assertion examples:

File root = new File("root");

// The following assertion succeeds:
assertThat(new File(root, "sub-dir-2")).isEmptyDirectory();

// The following assertions fail:
assertThat(root).isEmptyDirectory();
assertThat(new File(root, "sub-dir-1")).isEmptyDirectory();

isNotEmptyDirectory assertion examples:

File root = new File("root");

// The following assertions succeed:
assertThat(root).isNotEmptyDirectory();
assertThat(new File(root, "sub-dir-1")).isNotEmptyDirectory();

// The following assertion fails:
 assertThat(new File(root, "sub-dir-2")).isNotEmptyDirectory();

Add hasMessageContainingAll and hasMessageNotContainingAny to throwable assertions

These assertions are the equivalent of hasMessageContaining and hasMessageNotContaining but accepting multiple String parameters instead of only one.

Example:

Throwable throwableWithMessage = new IllegalArgumentException("wrong amount 123");
Throwable throwableWithoutMessage = new IllegalArgumentException();

// assertion will pass:
assertThat(throwableWithMessage).hasMessageContainingAll("amount", "123")
                                .hasMessageNotContainingAny("foo", "234");

assertThat(throwableWithoutMessage).hasMessageNotContainingAny("234");

// assertions will fail:
assertThat(throwableWithMessage).hasMessageContainingAll("234");
assertThat(throwableWithoutMessage).hasMessageContainingAll("123");

assertThat(throwableWithMessage).hasMessageNotContainingAny("foo", "amount");

The same assertions have been added to ThrowableAssertAlternative with these names withMessageContainingAll and withMessageNotContainingAny:

Throwable illegalArgumentException = new IllegalArgumentException("wrong amount 123");

// assertions will pass
assertThatExceptionOfType(Throwable.class)
          .isThrownBy(() -> {throw illegalArgumentException;})
          .withMessageContainingAll("amount", "123")
          .withMessageNotContainingAny("foo", "234");

Allow using any custom assertions in soft assertions

The new check​ method catches and collect assertion errors coming from standard and custom assertions.

Example:

SoftAssertions softly = new SoftAssertions();

// custom assertions
softly.check(() -> LotrAssertions.assertThat(frodo).hasName("Frodon"));
softly.check(() -> LotrAssertions.assertThat(frodo).hasName("Frodo"));

// standard assertions
softly.assertThat("foo").startsWith("bar");
// could be written with check like (but it's as elegant as the standard use):
// softly.check(() -> Assertions.assertThat("foo").startsWith("bar"));

// 2 errors: "foo" does not start with "bar" and frodo's name is not "Frodon"
assertThat(softly.errorsCollected()).hasSize(2);

Add containsExactlyInAnyOrderEntriesOf to map assertions

Verifies that the actual map contains only the given entries and nothing else, in any order.

This is the same assertion as containsOnly(Map.Entry…​ entries), it simply handles the conversion of Map.entrySet() to array.

Example :

Map<Ring, TolkienCharacter> ringBearers = newLinkedHashMap(entry(oneRing, frodo),
                                                           entry(nenya, galadriel),
                                                           entry(narya, gandalf));
// assertion will pass
assertThat(ringBearers).containsExactlyInAnyOrderEntriesOf(newLinkedHashMap(entry(oneRing, frodo),
                                                                            entry(nenya, galadriel),
                                                                            entry(narya, gandalf)));
// assertion will pass although actual and expected order differ
assertThat(ringBearers).containsExactlyInAnyOrderEntriesOf(newLinkedHashMap(entry(nenya, galadriel),
                                                                            entry(narya, gandalf),
                                                                            entry(oneRing, frodo)));
// assertion will fail as actual does not contain all entries of expected
assertThat(ringBearers).containsExactlyInAnyOrderEntriesOf(newLinkedHashMap(entry(oneRing, frodo),
                                                                            entry(nenya, galadriel),
                                                                            entry(oneRing, frodo)));
// assertion will fail as actual and expected have different sizes
assertThat(ringBearers).containsExactlyInAnyOrderEntriesOf(newLinkedHashMap(entry(oneRing, frodo),
                                                                            entry(nenya, galadriel),
                                                                            entry(narya, gandalf),
                                                                            entry(narya, gandalf)));

Add isCloseToUtcNow to LocalDateTime and OffsetDateTime assertions

Verifies that the actual LocalDateTime/OffsetDateTime is close to the current date and time on the UTC timezone, according to the given offset.

You can build the offset parameter using Assertions.within(long, TemporalUnit) or Assertions.byLessThan(long, TemporalUnit).

If the difference is equal to the offset, the assertion succeeds.

Example with LocalDateTime:

LocalDateTime actual = LocalDateTime.now(Clock.systemUTC());

// assertion will pass if executed less than one second after actual was built
assertThat(actual).isCloseToUtcNow(byLessThan(1, ChronoUnit.SECONDS));

// assertion will fail
assertThat(actual.plusSeconds(2)).isCloseToUtcNow(within(1, ChronoUnit.SECONDS));

The same example works with OffsetDateTime by simply defining actual as:

OffsetDateTime actual = OffsetDateTime.now(Clock.systemUTC());

Add support for combined millisecond and timezone parsing

Add yyyy-MM-dd HH:mm:ss.SSSX to the default date formats AssertJ supports in Date assertions that take a String parameter representating a Date.

Here’s an example of string following this format: "2003-04-26T00:00:00.123+00:00".

Example:

// GIVEN
SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
isoFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
// WHEN
Date date = isoFormat.parse("2003-04-26T00:00:00.123");
// THEN
assertThat(date).isEqualTo("2003-04-26T00:00:00.123+00:00");

Add support for Optional in the new recursive comparison

The recursive comparison added in 3.12.0 now compares Optional values recursively instead of comparing Optional with equals. This is consistent with comparing list elements by elements as an Optional can be seen as a list with at most one element.

Example:

// Song constructor parameters: song, author and coAuthor (optional)
Song song = new Song("I Can't Get No Satisfaction", new Author("Mick Jagger"), new Author("Keith Richards"));
Song expectedSong = new Song("I Can't Get No Satisfaction", new Author("Mick Jagger"), new Author("Keith Richards"));
// THEN
assertThat(song).usingRecursiveComparison()
                .isEqualTo(expectedSong);

where Song and Author don’t override equals:

class Song {

  Author author;
  Optional<Author> coAuthor;
  String song;

  Song(String song, Author author, Author coAuthor) {
    this.song = song;
    this.author = author;
    this.coAuthor = Optional.ofNullable(coAuthor);
  }

  // no equals!
}

class Author {

  String name;

  Author(String name) {
    this.name = name;
  }

  String getName() {
    return name;
  }

  // no equals!
}

If we fail the test ...

Song song = new Song("I Can't Get No Satisfaction", new Author("Mick Jagger"), new Author("Jimi Hendrix"));
Song expectedSong = new Song("I Can't Get No Satisfaction", new Author("Mick Jagger"), new Author("Keith Richards"));
// FAIL
assertThat(song).usingRecursiveComparison()
                .isEqualTo(expectedSong);

... here’s the error reported:

Expecting:
  <Song [author=Mick Jagger, coAuthor=Optional[Jimi Hendrix], song=I Can't Get No Satisfaction]>
to be equal to:
  <Song [author=Mick Jagger, coAuthor=Optional[Keith Richards], song=I Can't Get No Satisfaction]>
when recursively comparing field by field, but found the following difference:

field/property 'coAuthor.value.name' differ:
- actual value   : "Jimi Hendrix"
- expected value : "Keith Richards"

The recursive comparison was performed with this configuration:
- overridden equals methods were used in the comparison
- these types were compared with the following comparators:
  - java.lang.Double -> DoubleComparator[precision=1.0E-15]
  - java.lang.Float -> FloatComparator[precision=1.0E-6]
- actual and expected objects and their fields were compared field by field recursively even if they were not of the same type, this allows for example to compare a Person to a PersonDto (call strictTypeChecking(true) to change that behavior).

Allow ignoring collection order in the new recursive comparison

The recursive comparison added in 3.12.0 can now ignore collection order in all fields in the object under test, this is handy when comparing list to set fields where only the content is relevant but not the order.

Example:

public class Person {
  String name;
  List<Person> friends = new ArrayList<>();
}

Person sherlock1 = new Person("Sherlock Holmes");
sherlock1.friends.add(new Person("Dr. John Watson"));
sherlock1.friends.add(new Person("Molly Hooper"));

Person sherlock2 = new Person("Sherlock Holmes");
sherlock2.friends.add(new Person("Molly Hooper"));
sherlock2.friends.add(new Person("Dr. John Watson"));

// assertion succeeds as all fields collection order is ignored in the comparison
assertThat(sherlock1).usingRecursiveComparison()
                     .ignoringCollectionOrder()
                     .isEqualTo(sherlock2);

// assertion fails as fields collection order is not ignored in the comparison
assertThat(sherlock1).usingRecursiveComparison()
                     .isEqualTo(sherlock2);

Propagate value type with extracting(Function)

extracting(Function) learned to propagate the type parameter of the resulting ObjectAssert allowing then to chain other type aware methods (e.g. additional extracting).

Example:

// Old implementation
assertThat(yoda).extracting(Jedi::getName) // ObjectAssert<Object>
                .extracting(String::length) // Not compiling
                .isEqualTo(4);

// New implementation
assertThat(yoda).extracting(Jedi::getName) // ObjectAssert<String>
                .extracting(String::length)  // Compiling!
                .isEqualTo(4);

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

7.1.6. AssertJ Core 3.12.1 Release notes

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

7.1.7. 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 to all the contributors of 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 problem 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)

7.2. AssertJ Guava

AssertJ Guava main documentation is still in http://joel-costigliola.github.io/assertj/assertj-guava.html until it is moved to this website.
The new release notes though will be published here.

Latest release notes:

The javadoc for this release can be found here: https://www.javadoc.io/doc/org.assertj/assertj-guava/3.3.0/index.html

7.2.1. AssertJ Guava 3.3.0 Release notes

Release date : 2019-11-09

Contributors

Thanks to chrisly42 and Stefano Cordio for their contributions!

New features

Improvements

  • AssertJ’s javadoc are now searchable.

  • Use beautiful AssertJ’s site code style for javadoc :)

  • Migrate to JUnit 5 and latest assertj-core version 3.14.0.

Fixed

  • Fix for OptionalAssert.contains() that was not working for primitive arrays. (chrisly42)

Deprecated

  • Deprecate org.assertj.guava.data.MapEntry for org.assertj.core.data.MapEntry

Add InstanceOfAssertFactories to allow chain specific type assertions

Add factories for ByteSource, Multimap, Multiset, Optional (guava) and Table to allow to chain specific type assertions from a value initially declared as a less specific type.

Let’s start with the problem asInstanceOf is solving: in the following example we would like to call Table assertions but this is not possible since value is declared as an Object thus only Object assertions are accessible.

// Given a Table declared as an Object
Object actual = HashBasedTable.<Integer, Integer, String> create();

// We would like to call Table assertions but this is not possible since value is declared as an Object
assertThat(actual).isEmpty(); // this does not compile !

Thanks to asInstanceOf we can now tell AssertJ to consider value as a Table in order to call Table assertions.
To do so we need to pass an InstanceOfAssertFactory that can build a TableAssert, fortunately you don’t have to write it, it is already available in InstanceOfAssertFactories!

// Given a Table declared as an Object
Object actual = HashBasedTable.<Integer, Integer, String> create();

// With asInstanceOf, we switch to specific Table assertion by specifying the InstanceOfAssertFactory for Table
assertThat(value).asInstanceOf(InstanceOfAssertFactories.TABLE)
                 .isEmpty();

AssertJ verifies that the actual value is compatible with the assertions InstanceOfAssertFactory is going to give access to.

InstanceOfAssertFactories provides static factories for all types AssertJ provides assertions for, additional factories can be created with custom InstanceOfAssertFactory instances.