AssertJ: fluent assertions for Java tests

AssertJ replaces JUnit's assertEquals and assertTrue with chains of typed checks that read like sentences and produce failure messages that show the actual data. This page explains how the fluent API picks the right checks, compares its failure messages with JUnit's, and runs soft assertions, recursive comparison, custom assertions, and the mistakes that make a test pass when it should fail.

Share

Contents

What AssertJ is and how its fluent API works

JUnit's own assertions are a handful of static methods: assertEquals(expected, actual), assertTrue(condition), assertThrows. They work for anything, but they know nothing about the values they compare, so a failed assertTrue can only say that something was false. AssertJ is a separate assertion library, usable with JUnit 4, 5 and 6 and other test frameworks, built around one entry point: assertThat(actual).

assertThat is overloaded for hundreds of types. The compiler picks the overload from the static type of the argument, and each returns an assertion object for that type: a ListAssert for a list, a LocalDateAssert for a date, a BigDecimalAssert for a decimal. Every check returns the same assertion object again, so checks chain: assertThat(name).startsWith("A").hasSize(3). Because the assertion object knows its type, the IDE offers only checks that make sense, and the failure message can describe the actual value in detail. Nothing is checked until a method such as isEqualTo is called, which is the source of AssertJ's best-known trap, shown below.

AssertJ versions
VersionJavaNotes
1.x (2013)6Fork of the FEST-Assert library
2.x7Maintenance line for Java 7 projects
3.x (from 2015)8+Lambdas, assertThatThrownBy, soft assertions, recursive comparison (3.12+); 3.27 used here

The tests below were run with AssertJ 3.27 and JUnit 5.12 on JDK 21, using the launcher from the JUnit 5 page.

Everyday assertions and their failure messages

The first three tests pass and show typical AssertJ checks. The next three fail on purpose, each with a different kind of assertion, so their messages can be compared. The last one uses soft assertions with two wrong expectations.

Java
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.tuple;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.assertj.core.api.SoftAssertions;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

class AssertJExamplesTest {

    record Order(String id, String customer, BigDecimal total, LocalDate placed) {
    }

    static final List<Order> ORDERS = List.of(
            new Order("o1", "ana", new BigDecimal("19.90"), LocalDate.of(2026, 1, 3)),
            new Order("o2", "ben", new BigDecimal("5.00"), LocalDate.of(2026, 1, 9)),
            new Order("o3", "ana", new BigDecimal("42.10"), LocalDate.of(2026, 2, 1)));

    @Test
    @DisplayName("collections: filter, extract and compare in one chain")
    void collections() {
        assertThat(ORDERS)
                .hasSize(3)
                .filteredOn(o -> o.customer().equals("ana"))
                .extracting(Order::id, Order::total)
                .containsExactly(tuple("o1", new BigDecimal("19.90")),
                        tuple("o3", new BigDecimal("42.10")));
    }

    @Test
    @DisplayName("strings, numbers, dates, optionals and maps")
    void valueTypes() {
        assertThat("INV-2026-0042").startsWith("INV-").endsWith("0042").hasSize(13);
        assertThat(new BigDecimal("19.9")).isEqualByComparingTo("19.90");   // ignores scale
        assertThat(LocalDate.of(2026, 1, 9)).isAfter("2026-01-01").isBefore("2026-02-01");
        assertThat(Optional.of("ana")).contains("ana");
        assertThat(Map.of("ana", 2, "ben", 1)).containsEntry("ana", 2).doesNotContainKey("cho");
    }

    @Test
    @DisplayName("exceptions: type, message and cause")
    void exceptions() {
        assertThatThrownBy(() -> Integer.parseInt("12x"))
                .isInstanceOf(NumberFormatException.class)
                .hasMessageContaining("12x");
    }

    @Test
    @DisplayName("failure message: JUnit assertTrue")
    void junitMessage() {
        assertTrue(ORDERS.stream().anyMatch(o -> o.customer().equals("cho")));
    }

    @Test
    @DisplayName("failure message: AssertJ")
    void assertjMessage() {
        assertThat(ORDERS).extracting(Order::customer).contains("cho");
    }

    @Test
    @DisplayName("failure message: BigDecimal scale with assertEquals")
    void scaleTrap() {
        assertEquals(new BigDecimal("19.9"), ORDERS.get(0).total());
    }

    @Test
    @DisplayName("soft assertions collect every failure")
    void soft() {
        Order o = ORDERS.get(1);
        SoftAssertions softly = new SoftAssertions();
        softly.assertThat(o.customer()).as("customer").isEqualTo("ben");
        softly.assertThat(o.total()).as("total").isGreaterThan(new BigDecimal("10"));
        softly.assertThat(o.placed()).as("placed").isEqualTo("2026-01-10");
        softly.assertAll();
    }
}

Output:

Output
FAIL  failure message: AssertJ
      AssertionError: 
Expecting ArrayList:
  ["ana", "ben", "ana"]
to contain:
  ["cho"]
but could not find the following element(s):
  ["cho"]

FAIL  failure message: BigDecimal scale with assertEquals
      AssertionFailedError: expected: <19.9> but was: <19.90>
PASS  exceptions: type, message and cause
FAIL  failure message: JUnit assertTrue
      AssertionFailedError: expected: <true> but was: <false>
FAIL  soft assertions collect every failure
      AssertJMultipleFailuresError: 
Multiple Failures (2 failures)
-- failure 1 --
[total] 
Expecting actual:
  5.00
to be greater than:
  10
at AssertJExamplesTest.soft(AssertJExamplesTest.java:79)
-- failure 2 --
[placed] 
expected: 2026-01-10 (java.time.LocalDate)
 but was: 2026-01-09 (java.time.LocalDate)
at AssertJExamplesTest.soft(AssertJExamplesTest.java:80)
PASS  collections: filter, extract and compare in one chain
PASS  strings, numbers, dates, optionals and maps
tests: 7, passed: 3, failed: 4, aborted: 0, skipped: 0

What the results show

Three tests passed and four failed on purpose:

  • Collections: filteredOn keeps Ana's orders, extracting pulls two fields from each, and containsExactly checks them in order with tuple. The JUnit equivalent needs a stream pipeline and a separate list to compare against.
  • Typed checks: after assertThat, the IDE offers only the checks that make sense for the type: startsWith for strings, isAfter for dates (with ISO strings accepted for convenience), containsEntry for maps.
  • Failure messages: the same mistake, looking for a customer called "cho", gave two very different reports. JUnit's assertTrue can only say "expected: <true> but was: <false>"; AssertJ shows the actual list, what it should contain, and what is missing. When a test fails in CI, that difference decides whether you can fix it from the log alone.
  • BigDecimal: assertEquals failed on 19.9 versus 19.90 because BigDecimal.equals compares the scale. AssertJ's isEqualByComparingTo, used in the second test, compares the numeric value and passed.
  • Soft assertions: SoftAssertions ran all three checks and reported both failures together, each labelled with its as(...) description and line number. Normal assertions stop at the first failure.
  • Exceptions: assertThatThrownBy checks the type and the message in one chain.

Exceptions and described values

Exception tests are where JUnit's assertThrows and AssertJ differ most. AssertJ can check the type, the message and the cause chain in one statement, and it can label any value so that a failure explains what the number means. The code under test wraps an IOException in an UncheckedIOException, a common pattern, so there is a cause to check. Two tests fail on purpose.

Java
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.catchThrowable;

import java.io.IOException;
import java.io.UncheckedIOException;
import org.junit.jupiter.api.Test;

class ExceptionsTest {

    static String load(String name) {
        if (name.isBlank()) {
            throw new IllegalArgumentException("name is blank");
        }
        try {
            throw new IOException("disk full while reading " + name);
        } catch (IOException e) {
            throw new UncheckedIOException("cannot load " + name, e);
        }
    }

    @Test
    void typeMessageAndCause() {
        assertThatExceptionOfType(UncheckedIOException.class)
                .isThrownBy(() -> load("report"))
                .withMessage("cannot load report")
                .withCauseInstanceOf(IOException.class)
                .havingCause().withMessageContaining("disk full");
    }

    @Test
    void catchThenAssert() {
        Throwable t = catchThrowable(() -> load(" "));       // arrange-act-assert style
        assertThat(t).isInstanceOf(IllegalArgumentException.class).hasMessage("name is blank");
    }

    @Test
    void doesNotThrow() {
        assertThatCode(() -> Integer.parseInt("42")).doesNotThrowAnyException();
    }

    @Test
    void wrongExpectation() {
        assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() -> load("x"));
    }

    @Test
    void describedPrimitive() {
        int retries = 4;
        assertThat(retries).as("retries after a timeout").isLessThanOrEqualTo(3);
    }
}

Output:

Output
PASS  doesNotThrow()
PASS  typeMessageAndCause()
FAIL  wrongExpectation()
      AssertionError: 
Expecting actual throwable to be an instance of:
  java.lang.IllegalStateException
but was:
  java.io.UncheckedIOException: cannot load x
	at ExceptionsTest.load(ExceptionsTest.java:19)
	at ExceptionsTest.lambda$wrongExpectation$3(ExceptionsTest.java:45)
	at org.assertj.core.api.ThrowableAssert.catchThrowable(ThrowableAssert.java:66)
	...(71 remaining lines not displayed - this can be changed with Assertions.setMaxStackTraceElementsDisplayed)
FAIL  describedPrimitive()
      AssertionError: [retries after a timeout] 
Expecting actual:
  4
to be less than or equal to:
  3 
PASS  catchThenAssert()
tests: 5, passed: 3, failed: 2, aborted: 0, skipped: 0
  • typeMessageAndCause checked the outer exception's type and exact message, the cause's type, and with havingCause() the cause's own message. With assertThrows each of those is a separate statement.
  • catchThrowable captures the exception as a value, so the test keeps the arrange, act, assert layout; assertThatCode(...).doesNotThrowAnyException() makes "this must not throw" explicit instead of implicit.
  • wrongExpectation failed, and the report names both the expected type and the exception that was actually thrown, with its message, so the mismatch is visible at once.
  • describedPrimitive failed with the description "retries after a timeout" in square brackets before the values. A bare "Expecting 4 to be less than or equal to 3" would leave the reader guessing which number is wrong; as(...) costs one call.

Comparing objects field by field

Many classes, such as DTOs and JPA entities, do not override equals, or include a generated ID that differs between test runs. AssertJ's recursive comparison compares such objects field by field. The Customer class below has no equals, and the three tests compare it in different ways.

Java
import static org.assertj.core.api.Assertions.assertThat;

import java.math.BigDecimal;
import java.util.List;
import org.junit.jupiter.api.Test;

// Comparing objects field by field, without relying on their equals method
class RecursiveComparisonTest {

    // A mutable class without equals, as many DTOs and JPA entities are
    static class Customer {
        String name;
        BigDecimal balance;
        List<String> tags;
        long id;                                     // generated, differs between runs

        Customer(long id, String name, String balance, List<String> tags) {
            this.id = id;
            this.name = name;
            this.balance = new BigDecimal(balance);
            this.tags = tags;
        }

        @Override
        public String toString() {
            return "Customer " + id + " " + name;   // no equals: only toString is overridden
        }
    }

    final Customer expected = new Customer(0, "Ana", "10.0", List.of("vip", "eu"));

    @Test
    void isEqualToUsesEquals() {
        Customer actual = new Customer(41, "Ana", "10.0", List.of("vip", "eu"));
        assertThat(actual).isEqualTo(expected);      // Object.equals: different instances
    }

    @Test
    void recursiveComparison() {
        Customer actual = new Customer(41, "Ana", "10.00", List.of("eu", "vip"));
        assertThat(actual).usingRecursiveComparison()
                .ignoringFields("id")
                .ignoringCollectionOrder()
                .withComparatorForType(BigDecimal::compareTo, BigDecimal.class)
                .isEqualTo(expected);
    }

    @Test
    void recursiveComparisonReportsEveryDifference() {
        Customer actual = new Customer(41, "Anna", "12.50", List.of("vip"));
        assertThat(actual).usingRecursiveComparison().ignoringFields("id").isEqualTo(expected);
    }
}

Output:

Output
FAIL  isEqualToUsesEquals()
      AssertionFailedError: 
expected: Customer 0 Ana
 but was: Customer 41 Ana
PASS  recursiveComparison()
FAIL  recursiveComparisonReportsEveryDifference()
      AssertionError: 
Expecting actual:
  Customer 41 Anna
to be equal to:
  Customer 0 Ana
when recursively comparing field by field, but found the following 3 differences:

field/property 'balance' differ:
- actual value  : 12.50
- expected value: 10.0
Compared objects have java types and were thus compared with equals method

field/property 'name' differ:
- actual value  : "Anna"
- expected value: "Ana"
Compared objects have java types and were thus compared with equals method

field/property 'tags' differ:
- actual value  : ["vip"]
- expected value: ["vip", "eu"]
actual and expected values are collections of different size, actual size=1 when expected size=2

The recursive comparison was performed with this configuration:
- the following fields were ignored in the comparison: id
- no equals methods were used in the comparison EXCEPT for java JDK types since introspecting JDK types is forbidden in java 17+ (use withEqualsForType to register a specific way to compare a JDK type if you need it)
- these types were compared with the following comparators:
  - java.lang.Double -> DoubleComparator[precision=1.0E-15]
  - java.lang.Float -> FloatComparator[precision=1.0E-6]
  - java.nio.file.Path -> lexicographic comparator (Path natural order)
- 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).
- the introspection strategy used was: DefaultRecursiveComparisonIntrospectionStrategy

tests: 3, passed: 1, failed: 2, aborted: 0, skipped: 0
  • isEqualTo failed although every relevant field matched, because without equals it compares identities. The message shows only the two toString values, which here look different only because of the ID.
  • The recursive comparison passed with three adjustments: it ignored the generated id, ignored the order of tags, and compared BigDecimal values with compareTo, so 10.00 matched 10.0.
  • With real differences, the report listed all three at once, name, balance and tags, with actual and expected values and the configuration used. Fixing a DTO mapping from such a report needs no debugger.
  • As the message says, JDK types such as BigDecimal and String are compared with equals, because Java 17 forbids reflection into JDK internals. That is why the comparator for BigDecimal had to be registered explicitly.

Custom assertions, allSatisfy and assumptions

For domain types that appear in many tests, a custom assertion class makes tests read like the business rules and makes failures speak the domain's language. AssertJ supports this by extending AbstractAssert. The class also shows allSatisfy, which applies a group of checks to every element, and assumeThat, AssertJ's version of an assumption.

Java
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assumptions.assumeThat;

import java.math.BigDecimal;
import java.util.List;
import org.assertj.core.api.AbstractAssert;
import org.junit.jupiter.api.Test;

class CustomAssertTest {

    record Order(String id, BigDecimal total, String status) {
    }

    // A domain-specific assertion: reads like the business rule and reports in its terms
    static final class OrderAssert extends AbstractAssert<OrderAssert, Order> {
        OrderAssert(Order actual) {
            super(actual, OrderAssert.class);
        }

        static OrderAssert assertThatOrder(Order actual) {
            return new OrderAssert(actual);
        }

        OrderAssert isPaid() {
            isNotNull();
            if (!actual.status().equals("PAID")) {
                failWithMessage("Expected order %s to be PAID but was %s", actual.id(),
                        actual.status());
            }
            return this;
        }

        OrderAssert hasTotal(String total) {
            if (actual.total().compareTo(new BigDecimal(total)) != 0) {
                failWithMessage("Expected order %s to total %s but was %s", actual.id(), total,
                        actual.total());
            }
            return this;
        }
    }

    static final List<Order> ORDERS = List.of(new Order("o1", new BigDecimal("9.50"), "PAID"),
            new Order("o2", new BigDecimal("20.00"), "OPEN"));

    @Test
    void customAssertPasses() {
        OrderAssert.assertThatOrder(ORDERS.get(0)).isPaid().hasTotal("9.5");
    }

    @Test
    void customAssertFails() {
        OrderAssert.assertThatOrder(ORDERS.get(1)).hasTotal("20").isPaid();
    }

    @Test
    void allSatisfy() {
        assertThat(ORDERS).allSatisfy(o -> {
            assertThat(o.id()).startsWith("o");
            assertThat(o.total()).isPositive();
        });
    }

    @Test
    void assumption() {
        assumeThat(System.getenv("PAYMENT_SANDBOX")).as("sandbox URL").isNotNull();
    }
}

Output:

Output
ABORT  assumption()
      TestAbortedException: assumption was not met due to: [sandbox URL] 
Expecting actual not to be null
PASS  allSatisfy()
FAIL  customAssertFails()
      AssertionError: Expected order o2 to be PAID but was OPEN
PASS  customAssertPasses()
tests: 4, passed: 2, failed: 1, aborted: 1, skipped: 0
  • customAssertPasses checked that order o1 is paid and totals 9.5; hasTotal uses compareTo, so the stored 9.50 matched.
  • customAssertFails failed with "Expected order o2 to be PAID but was OPEN", written by failWithMessage. A generic assertion would have said that "OPEN" was not "PAID" without naming the order.
  • allSatisfy passed because both orders start with "o" and have a positive total. If one failed, the report would name the element.
  • assumeThat aborted the last test, because PAYMENT_SANDBOX was not set, and JUnit reported it as aborted rather than failed.

Tests that pass but check nothing

The most dangerous assertion bugs are the ones that never fail. Each of the first three tests below contains such a bug and passes; the fourth shows the corrected checks, and it fails, because the data really does contain a duplicate.

Java
import static org.assertj.core.api.Assertions.assertThat;

import java.util.List;
import org.assertj.core.api.SoftAssertions;
import org.junit.jupiter.api.Test;

// Each of these tests PASSES, although every one of them checks the wrong thing
class PitfallsTest {

    static final List<String> STEPS = List.of("validate", "charge", "ship", "ship");

    @Test
    void noCheckAfterAssertThat() {
        assertThat(STEPS.isEmpty());                  // asserts nothing at all
    }

    @Test
    void containsIgnoresOrderAndExtras() {
        assertThat(STEPS).contains("ship", "validate");   // wrong order, a duplicate: passes
    }

    @Test
    @SuppressWarnings("unused")
    void softAssertionsNeverReported() {
        SoftAssertions softly = new SoftAssertions();
        softly.assertThat(STEPS).hasSize(99);         // collected, but assertAll() is missing
    }

    @Test
    void correctVersions() {
        SoftAssertions.assertSoftly(softly -> {
            softly.assertThat(STEPS.isEmpty()).isFalse();
            softly.assertThat(STEPS).containsExactly("validate", "charge", "ship", "ship");
            softly.assertThat(STEPS).doesNotHaveDuplicates();
        });
    }
}

Output:

Output
PASS  noCheckAfterAssertThat()
PASS  softAssertionsNeverReported()
PASS  containsIgnoresOrderAndExtras()
FAIL  correctVersions()
      AssertJMultipleFailuresError: 
Multiple Failures (1 failure)
-- failure 1 --
Found duplicate(s):
  ["ship"]
in:
  ["validate", "charge", "ship", "ship"]
at PitfallsTest.lambda$correctVersions$0(PitfallsTest.java:34)
tests: 4, passed: 3, failed: 1, aborted: 0, skipped: 0
  • assertThat(STEPS.isEmpty()) with no check after it creates an assertion object and throws it away. The test passed although the list is not empty. Static analysis tools such as Error Prone and SonarQube flag this pattern.
  • contains("ship", "validate") passed even though the order is wrong and "ship" appears twice: contains checks only that the elements are present somewhere. containsExactly checks order, size and duplicates.
  • The soft assertion expecting 99 elements failed internally, but nothing called assertAll(), so the failure was never reported. SoftAssertions.assertSoftly(...), used in the last test, calls it automatically, as does SoftAssertionsExtension.
  • correctVersions reported "Found duplicate(s): [ship]". Correct checks find real problems in the data, which is the point of writing them.

Choosing assertions

Common mistakes and the assertion to use instead
MistakeUse instead
assertThat(x.isValid()); with no check after itAsserts nothing; the test always passes. Write assertThat(x.isValid()).isTrue()
assertThat(list).contains(a, b) when order matterscontains ignores order and extra elements; use containsExactly
Soft assertions without assertAll()Failures are collected but never reported. The SoftAssertionsExtension or SoftAssertions.assertSoftly(...) calls it for you
isEqualTo on BigDecimalCompares scale; use isEqualByComparingTo
isEqualTo on objects without equalsusingRecursiveComparison()
Long chains of generic checks on a domain objectA custom AbstractAssert subclass
assertTrue(list.contains(x))assertThat(list).contains(x), for a useful failure message

Moving an existing suite to AssertJ can be done one test at a time, since both assertion styles work side by side. Two habits change along the way. The actual value always comes first, in assertThat(actual), which removes the swapped-argument mistake that makes assertEquals(expected, actual) print misleading messages. And each check states its intent by name, such as containsExactly or isEqualByComparingTo, so a reviewer can see what a test really checks. OpenRewrite has recipes that convert JUnit assertions automatically.

AssertJ works with any test framework; with Mockito it is commonly used to check values captured with ArgumentCaptor.