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.
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)assertThrowsassertTrueassertThat(actual)
assertThatListAssertLocalDateAssertBigDecimalAssertassertThat(name).startsWith("A").hasSize(3)isEqualTo
| Version | Java | Notes |
|---|---|---|
| 1.x (2013) | 6 | Fork of the FEST-Assert library |
| 2.x | 7 | Maintenance line for Java 7 projects |
| 3.x (from 2015) | 8+ | Lambdas, assertThatThrownBy |
The tests below were run with AssertJ 3.27 and JUnit 5.12 on JDK 21, using the launcher from the
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.
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:
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:
keeps Ana's orders,filteredOn pulls two fields from each, andextracting checks them in order withcontainsExactly . The JUnit equivalent needs a stream pipeline and a separate list to compare against.tuple - Typed checks: after
, the IDE offers only the checks that make sense for the type:assertThat for strings,startsWith for dates (with ISO strings accepted for convenience),isAfter for maps.containsEntry - Failure messages: the same mistake, looking for a customer called "cho", gave two very different reports. JUnit's
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.assertTrue - BigDecimal:
failed on 19.9 versus 19.90 becauseassertEquals compares the scale. AssertJ'sBigDecimal.equals , used in the second test, compares the numeric value and passed.isEqualByComparingTo - Soft assertions:
ran all three checks and reported both failures together, each labelled with itsSoftAssertions description and line number. Normal assertions stop at the first failure.as(...) - Exceptions:
checks the type and the message in one chain.assertThatThrownBy
Exceptions and described values
Exception tests are where JUnit's assertThrowsIOExceptionUncheckedIOException
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:
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
checked the outer exception's type and exact message, the cause's type, and withtypeMessageAndCause the cause's own message. WithhavingCause() each of those is a separate statement.assertThrows captures the exception as a value, so the test keeps the arrange, act, assert layout;catchThrowable makes "this must not throw" explicit instead of implicit.assertThatCode(...).doesNotThrowAnyException() 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.wrongExpectation 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;describedPrimitive costs one call.as(...)
Comparing objects field by field
Many classes, such as DTOs and JPA entities, do not override equalsCustomerequals
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:
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
failed although every relevant field matched, because withoutisEqualTo it compares identities. The message shows only the twoequals values, which here look different only because of the ID.toString- The recursive comparison passed with three adjustments: it ignored the generated
, ignored the order ofid , and comparedtags values withBigDecimal , so 10.00 matched 10.0.compareTo - 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
andBigDecimal are compared withString , because Java 17 forbids reflection into JDK internals. That is why the comparator forequals had to be registered explicitly.BigDecimal
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 AbstractAssertallSatisfyassumeThat
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:
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
checked that order o1 is paid and totals 9.5;customAssertPasses useshasTotal , so the stored 9.50 matched.compareTo failed with "Expected order o2 to be PAID but was OPEN", written bycustomAssertFails . A generic assertion would have said that "OPEN" was not "PAID" without naming the order.failWithMessage passed because both orders start with "o" and have a positive total. If one failed, the report would name the element.allSatisfy aborted the last test, becauseassumeThat was not set, and JUnit reported it as aborted rather than failed.PAYMENT_SANDBOX
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.
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:
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
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.assertThat(STEPS.isEmpty()) passed even though the order is wrong and "ship" appears twice:contains("ship", "validate") checks only that the elements are present somewhere.contains checks order, size and duplicates.containsExactly- The soft assertion expecting 99 elements failed internally, but nothing called
, so the failure was never reported.assertAll() , used in the last test, calls it automatically, as doesSoftAssertions.assertSoftly(...) .SoftAssertionsExtension reported "Found duplicate(s): [ship]". Correct checks find real problems in the data, which is the point of writing them.correctVersions
Choosing assertions
| Mistake | Use instead |
|---|---|
assertThat(x.isValid()); | Asserts nothing; the test always passes. Write assertThat(x.isValid()).isTrue() |
assertThat(list).contains(a, b) | containscontainsExactly |
Soft assertions without assertAll() | Failures are collected but never reported. The SoftAssertionsExtensionSoftAssertions.assertSoftly(...) |
isEqualToBigDecimal | Compares scale; use isEqualByComparingTo |
isEqualToequals | usingRecursiveComparison() |
| Long chains of generic checks on a domain object | A custom AbstractAssert |
assertTrue(list.contains(x)) | assertThat(list).contains(x) |
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)assertEquals(expected, actual)containsExactlyisEqualByComparingTo
AssertJ works with any test framework; with ArgumentCaptor