Skip to lesson

Readable assertions with AssertJ

JUnit's assertEquals works, but long checks get hard to read and its failure messages show little. ShopLite's team wants tests that read like sentences and explain themselves when they fail.

assertThat(actual).isEqualTo(expected) and the assertj-core dependency

AssertJ is an assertion library whose checks read like sentences, such as assertThat(cart.itemCount()).isEqualTo(3). It runs inside JUnit tests, offers hundreds of type-specific checks and prints failure messages that show exactly what differed.

Write a check as assertThat(actual) followed by what you expect. The first program shows how such a chain works inside; the second runs real AssertJ next to JUnit.

XML
<dependency>    <groupId>org.assertj</groupId>    <artifactId>assertj-core</artifactId>    <version>3.27.7</version>    <scope>test</scope></dependency>

Example 1 · How a fluent assertion works: a tiny assertThat in plain Java

FluentAssertDemo.javaJava
class IntAssert {    private final int actual;    private String description = "";
    IntAssert(int actual) {        this.actual = actual;    }
    IntAssert as(String text) {                    // returns this, so calls can be chained        description = "[" + text + "] ";        return this;    }
    IntAssert isEqualTo(int expected) {        if (actual != expected) {            throw new AssertionError(description + "expected: " + expected + " but was: " + actual);        }        return this;    }
    IntAssert isBetween(int low, int high) {        if (actual < low || actual > high) {            throw new AssertionError(description + "expected " + actual + " to be between " + low + " and " + high);        }        return this;    }}
public class FluentAssertDemo {    static IntAssert assertThat(int actual) {        return new IntAssert(actual);    }
    public static void main(String[] args) {        assertThat(3).isBetween(1, 10).isEqualTo(3);        System.out.println("chained checks passed");
        try {            assertThat(1799).as("cart total").isEqualTo(1798);        } catch (AssertionError e) {            System.out.println(e.getMessage());        }        try {            assertThat(0).as("quantity").isBetween(1, 10);        } catch (AssertionError e) {            System.out.println(e.getMessage());        }    }}
Output
chained checks passed
[cart total] expected: 1798 but was: 1799
[quantity] expected 0 to be between 1 and 10

What this code does

  • assertThat wraps the actual value in an object, and every check returns this, which is what makes assertThat(3).isBetween(1, 10).isEqualTo(3) possible. AssertJ is built the same way, with a different assert class for each type.
  • as(...) only stores a label that later failure messages use, which is why it must come before the check it describes.

Example 2 · AssertJ basics next to JUnit

Runs in: a Maven project with JUnit 5 and AssertJ (shoplite-api: src/test/java/com/shoplite/cart)

Java
package com.shoplite.cart;
import static org.assertj.core.api.Assertions.assertThat;
import java.math.BigDecimal;
import org.junit.jupiter.api.Test;
class CartAssertJTest {
    @Test    void addingThreeNotebooksCountsThreeItems() {        Cart cart = new Cart();
        cart.add("NB-A5", new BigDecimal("60.00"), 3);
        assertThat(cart.itemCount()).isEqualTo(3);             // JUnit: assertEquals(3, cart.itemCount())        assertThat(cart.itemCount()).isPositive().isLessThan(100);    }
    @Test    void wrongExpectedValueShowsAClearMessage() {        Cart cart = new Cart();        cart.add("NB-A5", new BigDecimal("60.00"), 3);
        assertThat(cart.itemCount()).as("items in cart").isEqualTo(4);    // fails on purpose    }}
Sample output
[ERROR] com.shoplite.cart.CartAssertJTest.wrongExpectedValueShowsAClearMessage -- Time elapsed: 0.012 s <<< FAILURE!
org.opentest4j.AssertionFailedError: [items in cart]
expected: 4
 but was: 3

What this code does

  • Each assertion starts from the actual value, so it reads left to right: "assert that the item count is equal to 3". Chaining isPositive().isLessThan(100) checks two facts about the same value.
  • The failure puts the as(...) label in square brackets and lines up expected and actual on two lines. When run in an IDE, the same AssertionFailedError lets you open a side-by-side comparison.

assertThat(actual) (from org.assertj.core.api.Assertions) wraps the value you got and returns an object full of checks for its type. This style is called a fluent API: each call returns an object you can call the next method on. The actual value comes first, so the expected/actual mix-up of assertEquals cannot happen.

In shoplite-api the Spring Boot test starter already includes AssertJ; in a plain Maven project add assertj-core with test scope.

Collections: hasSize, contains, containsExactly, extracting

extracting turns a list of objects into a list of one field, like extracting(CartLine::sku), so one chain can check the SKU of every cart line. With several getters and tuple(...) it checks several fields per element.

A cart holds lines. Check how many there are, which SKUs they carry and in which order, all in one chain.

Example 3 · Collections: content, order and extracted fields

Runs in: a Maven project with JUnit 5 and AssertJ (shoplite-api: src/test/java/com/shoplite/cart)

Java
package com.shoplite.cart;
import static org.assertj.core.api.Assertions.assertThat;import static org.assertj.core.api.Assertions.tuple;
import java.math.BigDecimal;
import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;
class CartLinesAssertJTest {
    private Cart cart;
    @BeforeEach    void createCart() {        cart = new Cart();        cart.add("NB-A5", new BigDecimal("60.00"), 2);        cart.add("PEN-BLU", new BigDecimal("10.00"), 3);    }
    @Test    void linesKeepTheOrderItemsWereAdded() {        assertThat(cart.lines())                .hasSize(2)                .extracting(CartLine::sku)                .containsExactly("NB-A5", "PEN-BLU");    }
    @Test    void eachLineHasItsSkuAndQuantity() {        assertThat(cart.lines())                .extracting(CartLine::sku, CartLine::quantity)                .containsExactlyInAnyOrder(tuple("PEN-BLU", 3), tuple("NB-A5", 2));    }
    @Test    void wrongOrderIsReportedIndexByIndex() {        assertThat(cart.lines()).extracting(CartLine::sku)                .containsExactly("PEN-BLU", "NB-A5");                 // fails on purpose    }}
Sample output
[ERROR] com.shoplite.cart.CartLinesAssertJTest.wrongOrderIsReportedIndexByIndex -- Time elapsed: 0.015 s <<< FAILURE!
org.opentest4j.AssertionFailedError:
Expecting actual:
  ["NB-A5", "PEN-BLU"]
to contain exactly (and in same order):
  ["PEN-BLU", "NB-A5"]
but there were differences at these indexes:
  - element at index 0: expected "PEN-BLU" but was "NB-A5"
  - element at index 1: expected "NB-A5" but was "PEN-BLU"

What this code does

  • extracting(CartLine::sku) turns the list of lines into a list of SKUs, so one chain checks size, content and order. With JUnit alone this takes a loop or several assertEquals calls.
  • containsExactly cares about order and containsExactlyInAnyOrder does not. The failure lists both lists and every index that differs, which no hand-written assertEquals gives you.

hasSize(2), isEmpty(), contains("PEN-BLU") (present, in any order), containsExactly("NB-A5", "PEN-BLU") (exactly these, in this order) and containsExactlyInAnyOrder(...) check the content directly. extracting(CartLine::sku, CartLine::quantity) with tuple("NB-A5", 2) checks several fields per element.

Predict the output

Does the check pass?

The SKUs of the cart lines are ["NB-A5", "PEN-BLU"]. Pick the result.

Round 1 of 3

Is PEN-BLU somewhere in the list?

List<String> skus = List.of("NB-A5", "PEN-BLU");
assertThat(skus).contains("PEN-BLU");

Strings, numbers, BigDecimal and Optional

isEqualByComparingTo compares a BigDecimal with compareTo, so 1497.00 passes against 1497. Plain isEqualTo still compares the scale like equals, so it would fail.

Every type has its own checks. This test uses string, number, BigDecimal and Optional checks side by side.

Example 4 · Strings, numbers, BigDecimal and Optional

Runs in: a Maven project with JUnit 5 and AssertJ (shoplite-api: src/test/java/com/shoplite/cart)

Java
package com.shoplite.cart;
import static org.assertj.core.api.Assertions.assertThat;import static org.assertj.core.api.Assertions.within;
import java.math.BigDecimal;import java.util.Map;import java.util.Optional;
import org.junit.jupiter.api.Test;
class ValueChecksTest {
    private final Map<String, Integer> coupons = Map.of("FEST20", 20);
    Optional<Integer> discountFor(String code) {        return Optional.ofNullable(coupons.get(code));    }
    @Test    void skuFormat() {        assertThat("MOB-RN13").startsWith("MOB-").hasSize(8).matches("[A-Z0-9-]+");    }
    @Test    void averageRatingIsCloseToFourPointThree() {        assertThat((4 + 4 + 5) / 3.0).isCloseTo(4.33, within(0.01));    }
    @Test    void cartTotalByValue() {        Cart cart = new Cart();        cart.add("BK-CLEAN", new BigDecimal("499.00"), 3);
        assertThat(cart.total()).isEqualByComparingTo("1497");          // 1497.00 passes        assertThat(cart.total()).isEqualTo(new BigDecimal("1497.00"));  // isEqualTo compares the scale too    }
    @Test    void couponLookups() {        assertThat(discountFor("FEST20")).contains(20);        assertThat(discountFor("NOCODE")).isEmpty();    }}
Sample output
[INFO] Running com.shoplite.cart.ValueChecksTest
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.071 s -- in com.shoplite.cart.ValueChecksTest

What this code does

  • Every type gets its own vocabulary: startsWith and matches for strings, isCloseTo(..., within(...)) for doubles, contains and isEmpty for Optional. Chains read like a description of the value.
  • isEqualByComparingTo("1497") is AssertJ's answer to the BigDecimal scale problem: it uses compareTo, so 1497 and 1497.00 match. Use isEqualTo when the two decimals themselves are part of the promise.

Strings: startsWith, contains, matches(regex), isBlank(). Numbers: isPositive(), isBetween(1, 10), and isCloseTo(0.3, within(0.000001)) for doubles. For Optional: isPresent(), isEmpty(), contains(value) and hasValueSatisfying(...).

Fix the error

Fix the money check

Read the failure, then pick the line that fixes the test.

The cart total is right, but the check fails.

BigDecimal total = cart.total(); // 1497.00
assertThat(total).isEqualTo(new BigDecimal("1497"));

Error

org.opentest4j.AssertionFailedError:
expected: 1497
 but was: 1497.00

assertThatThrownBy and assertThatExceptionOfType

assertThatThrownBy(() -> call()) fails if nothing is thrown and otherwise lets you chain checks on the exception, such as isInstanceOf(...) and hasMessage(...).

The cart must refuse a quantity of 0. Check the exception type and its message in one chain.

Example 5 · Exceptions: assertThatThrownBy and assertThatExceptionOfType

Runs in: a Maven project with JUnit 5 and AssertJ (shoplite-api: src/test/java/com/shoplite/cart)

Java
package com.shoplite.cart;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.math.BigDecimal;
import org.junit.jupiter.api.Test;
class CartExceptionsAssertJTest {
    @Test    void zeroQuantityIsRejected() {        Cart cart = new Cart();
        assertThatThrownBy(() -> cart.add("NB-A5", new BigDecimal("60.00"), 0))                .isInstanceOf(IllegalArgumentException.class)                .hasMessage("Quantity must be at least 1");    }
    @Test    void removingAnUnknownSkuIsRejected() {        Cart cart = new Cart();
        assertThatExceptionOfType(IllegalArgumentException.class)                .isThrownBy(() -> cart.remove("PEN-BLU"))                .withMessageContaining("PEN-BLU");    }
    @Test    void wrongMessageIsShownInFull() {        Cart cart = new Cart();
        assertThatThrownBy(() -> cart.add("NB-A5", new BigDecimal("60.00"), 0))                .hasMessage("Quantity must be 1 or more");                  // fails on purpose    }}
Sample output
[ERROR] com.shoplite.cart.CartExceptionsAssertJTest.wrongMessageIsShownInFull -- Time elapsed: 0.014 s <<< FAILURE!
org.opentest4j.AssertionFailedError:
Expecting message to be:
  "Quantity must be 1 or more"
but was:
  "Quantity must be at least 1"

Throwable that failed the check:

java.lang.IllegalArgumentException: Quantity must be at least 1
	at com.shoplite.cart.Cart.add(Cart.java:14)
	...

What this code does

  • Both styles check that something was thrown, its type and its message, in one chain. withMessageContaining("PEN-BLU") is useful when the full message has parts you do not want to pin down.
  • When the message differs, AssertJ prints both messages and the stack trace of the real exception, so you see where it was thrown (Cart.java:14) without debugging.

hasMessageContaining checks part of the message. assertThatExceptionOfType(Type.class).isThrownBy(() -> call()).withMessage("...") says the type first and reads the other way round. Both do the same job as JUnit's assertThrows; pick one style per project.

Clearer failure messages, as() and SoftAssertions

SoftAssertions collects failures instead of stopping at the first one, like JUnit's assertAll: every failed check is reported together at the end of the assertSoftly block.

A cart line has the wrong quantity and the wrong total. See both failures in one report, each with a label.

Example 6 · SoftAssertions: every failed check in one report

Runs in: a Maven project with JUnit 5 and AssertJ (shoplite-api: src/test/java/com/shoplite/cart)

Java
package com.shoplite.cart;
import java.math.BigDecimal;
import org.assertj.core.api.SoftAssertions;import org.junit.jupiter.api.Test;
class CartLineSoftTest {
    @Test    void addingThreeNotebooksMakesOneCorrectLine() {        Cart cart = new Cart();        cart.add("NB-A5", new BigDecimal("60.00"), 3);        CartLine line = cart.lines().get(0);
        SoftAssertions.assertSoftly(softly -> {            softly.assertThat(line.sku()).as("sku").isEqualTo("NB-A5");            softly.assertThat(line.quantity()).as("quantity").isEqualTo(2);          // wrong on purpose            softly.assertThat(line.lineTotal()).as("line total").isEqualByComparingTo("150");   // wrong on purpose        });    }}
Sample output
[ERROR] com.shoplite.cart.CartLineSoftTest.addingThreeNotebooksMakesOneCorrectLine -- Time elapsed: 0.031 s <<< FAILURE!
org.assertj.core.error.AssertJMultipleFailuresError:
Multiple Failures (2 failures)
-- failure 1 --
[quantity]
expected: 2
 but was: 3
at CartLineSoftTest.lambda$addingThreeNotebooksMakesOneCorrectLine$0(CartLineSoftTest.java:18)
-- failure 2 --
[line total]
expected: 150
 but was: 180.00
at CartLineSoftTest.lambda$addingThreeNotebooksMakesOneCorrectLine$0(CartLineSoftTest.java:19)

What this code does

  • Inside assertSoftly, a failed check is recorded instead of thrown; at the end of the block all failures are reported together, each with its as(...) label and its line number.
  • This is AssertJ's version of JUnit's assertAll. Like assertAll, use it for the facets of one result, not to squeeze several behaviours into one test.

AssertJ's messages show what it expected and what it found, element by element for collections: Expecting actual: ["Pen", "Book"] to contain exactly (and in same order): ["Book", "Pen"], then the differing indexes. as("cart total"), placed before the check, adds a label: [cart total] expected: 1798 but was: 1799.

Next step

Check your understanding

10 quick questions