Skip to content
javahacks.dev
JUnit

How to Write Readable Assertions With JUnit 5 and AssertJ

Write assertions that say what they check and fail with a message you can act on, using JUnit 5 assertions and AssertJ's fluent style together.

6 min read
Summarize in AI
Flat illustration of a test report with one failing test, with the JUnit5, Jenkins and GitHub Actions logos.

An assertion is a sentence about your code. When it fails, the message should finish the sentence for you. A assertTrue(result) that fails with expected: <true> but was: <false> tells you something is wrong and nothing about what. This post collects the habits that make failures useful, with the JUnit 5 assertions first and AssertJ for the cases where it is clearly better. The framework tour is in the JUnit 5 handbook.

Choose the specific assertion

Instead ofWriteWhy
assertTrue(a == b)assertEquals(a, b)Failure prints both values
assertTrue(list.isEmpty())assertTrue(list.isEmpty(), "orders: " + list) or AssertJ isEmpty()Shows the contents
assertTrue(x == null)assertNull(x)Prints the actual value
assertTrue(a.equals(b))assertEquals(a, b)Same

The generic assertTrue loses all information. A specific assertion gives you the data for free.

Expected first

java
assertEquals(400, total.cents());       // expected, actual

When it fails, JUnit prints expected: <400> but was: <350>. Reverse the arguments and the message says the opposite of the truth, which sends you to the wrong side of the code.

Add a message only when it helps

java
assertEquals(3, order.lines().size(), () -> "lines for order " + order.id());

The supplier form builds the message only on failure, so an expensive message costs nothing on a pass. Do not write messages that restate the assertion, such as "sizes should be equal".

One behavior per test, many facts per behavior

A test about one result can check several properties of it. assertAll reports every failing one, not just the first:

java
assertAll("receipt",
    () -> assertEquals("ana", receipt.customer()),
    () -> assertEquals(400, receipt.totalCents()),
    () -> assertEquals("USD", receipt.currency()));

Three separate behaviors, such as "creates the receipt", "sends an email" and "writes an audit record", are three tests.

Collections and strings with AssertJ

JUnit's assertEquals(expectedList, actualList) fails with two toString dumps you have to diff by eye. AssertJ prints the missing and unexpected elements:

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

assertThat(names).containsExactly("ana", "ben");
assertThat(names).containsExactlyInAnyOrder("ben", "ana");
assertThat(message).startsWith("Order").contains("shipped");
assertThat(order.total()).isBetween(100L, 200L);

A failure in containsExactly lists which elements were missing and which were not expected, in order. spring-boot-starter-test brings AssertJ, and in other projects you add org.assertj:assertj-core with test scope. The two libraries live together; use the JUnit ones for simple values and AssertJ where the extra detail pays.

Assert the outcome, not the method calls

java
// brittle: checks how, not what
verify(repo).save(any());
verify(mailer, times(1)).send(any(), any());

// durable: checks the result
assertEquals(OrderStatus.PAID, orders.findById(id).orElseThrow().status());

Interactions are worth verifying when they are the observable outcome, like sending a message. Otherwise assert on state, as argued in what to mock and what to leave real.

Exceptions

Use assertThrows and check the message, as detailed in assertThrows and assertAll. AssertJ offers assertThatThrownBy(() -> ...).isInstanceOf(...).hasMessageContaining(...) for the same job.

What each failure looks like

An assertion is judged by the message it prints when it fails. This test class makes six assertions fail on purpose so the output can be compared. It runs on JUnit 6.0.0 with AssertJ 3.27.3.

AssertionsTest.javajava
record Order(String id, String status, int items) {}

@Test void junitEquals() { assertEquals("PAID", new Order("o1", "NEW", 2).status()); }

@Test void junitAll() {
    Order o = new Order("o1", "NEW", 2);
    assertAll("order",
            () -> assertEquals("PAID", o.status()),
            () -> assertEquals(3, o.items()));
}

@Test void junitMessage() { assertTrue(List.of("a", "b").contains("c"), "tag c should be present"); }

@Test void assertjList() {
    assertThat(List.of("java", "spring", "hibernate")).contains("quarkus").hasSize(2);
}

@Test void exception() {
    assertThrows(IllegalArgumentException.class, () -> { throw new IllegalStateException("boom"); });
}
Text
junitEquals:   expected: <PAID> but was: <NEW>

junitAll:      order (2 failures)
                 expected: <PAID> but was: <NEW>
                 expected: <3> but was: <2>

junitMessage:  tag c should be present ==> expected: <true> but was: <false>

assertjList:   Expecting ListN:
                 ["java", "spring", "hibernate"]
               to contain:
                 ["quarkus"]
               but could not find the following element(s):
                 ["quarkus"]

exception:     Unexpected exception type thrown, expected: <java.lang.IllegalArgumentException>
               but was: <java.lang.IllegalStateException>

Compare the messages. assertTrue(list.contains("c")) can say only "expected true but was false", and the reader needs the custom message to learn anything. The AssertJ version prints the whole list and the missing element without any message at all. That is the case for a specific assertion over a boolean one: the framework knows what you were checking and can describe it.

assertAll is the second useful result. Both wrong fields were reported, in one run. Without it, the first failing assertion ends the test, you fix one field, and discover the second on the next run. Group related checks about one object in assertAll.

The same object, compared by fields

Testing a record or an entity usually means checking several fields. Comparing them with isEqualTo on the whole object fails with a long toString, and field by field fails at the first mismatch. AssertJ's extracting reports all of them together.

java
assertThat(order)
        .extracting(Order::status, Order::items)
        .containsExactly("PAID", 3);
Text
Expecting actual:
  ["NEW", 2]
to contain exactly (and in same order):
  ["PAID", 3]
but some elements were not found:
  ["PAID", 3]
and others were not expected:
  ["NEW", 2]

For many fields, usingRecursiveComparison() compares two objects field by field and lists every difference, ignoring the fields you name with ignoringFields("id", "createdAt"). Use it for objects built by code, such as mapper output, where equals is not defined.

Do not assert on the shape of an exception message

assertThrows returns the exception, and tests commonly check its message. A message is wording, and wording changes. Assert the type, and where the content matters assert a stable property such as a code or the field name.

java
InvalidOrder e = assertThrows(InvalidOrder.class, () -> service.place(emptyOrder()));
assertThat(e.field()).isEqualTo("items");

If you must check text, check one fragment with contains, and not the full sentence. A test that breaks every time someone improves an error message teaches the team to update the test blindly, which removes its value.

Keep the failure message for a person who did not write the test

The reader of a red build is usually someone who has never seen the test. Name the test for the behaviour (rejectsAnOrderWithNoItems), prefer assertions whose own message says what was compared, and add as(...) to AssertJ chains where the subject is not obvious: assertThat(totals).as("totals per customer").containsEntry("c1", 120). The description is printed in front of the failure. Run the test once with the expectation deliberately wrong, as the class above does, and read the output as that stranger would.

Structure a test so the failure explains itself

Most of the value of a test is the story it tells when it fails, and three habits make the story short. Arrange, act and assert should be visibly separate, with a blank line between each, so the reader sees what was set up before looking at what was checked. The assertion should be on the result that matters to the caller, not on an intermediate field. And every test should fail for one reason: if a test has five unrelated assertions, a red result gives five suspects. Use assertAll when the facts belong to one behaviour, and split the test when they do not.

A final check is to break the code on purpose. Change the production logic to return the wrong value, run the test, and read the output as a stranger would. If the message already tells you the field, the expected value and the actual value, the assertion is good. If it says only that a condition was false, replace it with a more specific one. This takes a minute per test and is the cheapest quality control available for a test suite, since the test is rarely read until the day it fails.

Where this advice stops

Floating-point results need a tolerance: assertEquals(0.3, a + b, 1e-9). Equality of objects without equals compares references; use records, or AssertJ's usingRecursiveComparison(). Snapshot and golden-file tests have their own tools. The AssertJ documentation and the JUnit user guide on assertions are the primary references.

Also inTesting
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.