AssertJ: readable assertions and soft assertions
AssertJ is a library of fluent assertions with type-specific methods and a clear failure report. Through assertThat(actual) a failure shows both the actual and the expected value, so assertThat(list).contains(x) is more informative than assertThat(list.contains(x)).isTrue(). Soft assertions collect all failures and report them together, but they need assertAll(), assertSoftly or the SoftAssertionsExtension, otherwise the test stays green.
Java · Assertions and API
A test failed with "expected: true but was: false". Which field, which list, which expectation?
A good assertion does not only pass or fail, it explains the failure at a glance in the CI report. Plain assertTrue(list.contains(x)) does not do that. AssertJ builds the message from the structure of the assertion itself, so the report reads without running the test under a debugger.
How it works and why. Everything starts with assertThat(actual). The type of the actual value decides which methods are available: startsWith for a string, hasSize and contains for a list, isBetween for a number. The IDE suggests them after the dot, and on failure AssertJ prints both the expected and the actual value along with the name of the check ("Expecting list to contain …"). The order is always "actual, then expected", so there is no confusion over arguments as in assertEquals(expected, actual).
Example: before → after. The same checks in JUnit assertions:
// JUnit: argument order is easy to swap
assertEquals(user.name(), "Anna");
assertTrue(names.size() == 3);
assertTrue(names.contains("Anna"));
// message: expected: <true> but was: <false>
The same with AssertJ, plus several moves worth knowing by heart:
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
assertThat(user.name()).isEqualTo("Anna");
assertThat(names).hasSize(3).contains("Anna").doesNotHaveDuplicates();
assertThat(price).as("cart price").isBetween(10, 100);
assertThat(orders).extracting(Order::status)
.containsExactlyInAnyOrder("PAID", "NEW");
assertThat(actualOrder).usingRecursiveComparison()
.ignoringFields("id", "createdAt")
.isEqualTo(expectedOrder);
assertThatThrownBy(() -> service.pay(emptyCart))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("empty");
as("…")adds a description before the check. It appears in the report when the value alone says little (a 0 or afalse).extractingpulls a field out of a list of objects, so no manual loop or Stream is needed.usingRecursiveComparison()compares objects field by field even when the class has noequals. Generated fields (id, creation time) are excluded throughignoringFields.assertThatThrownBychecks the type and text of an exception. It is handier than try/catch with a manualfail().
Soft assertions. A hard assertion throws AssertionError at the first failure, and you do not see the rest. A soft one collects failures into a list and throws one report at the end:
Hard and soft assertion
Stops at the first
Three fields, two errors: the test shows one. Fix, rerun, see the second. Fits when the next check depends on the previous one.
Collects all
All failures in one report from a single run. Fits independent fields of one object.
The life of a soft assertion
SoftAssertions.assertSoftly(softly -> {
softly.assertThat(user.name()).isEqualTo("Anna");
softly.assertThat(user.role()).isEqualTo("admin");
softly.assertThat(user.active()).isTrue();
}); // assertAll() is called automatically
Inside assertSoftly the report is raised automatically at the end of the block. If you create new SoftAssertions() by hand, you must call softly.assertAll() yourself: without it failures are ignored and the test passes green. The most reliable option in JUnit 5/6 is the extension that calls assertAll for you:
@ExtendWith(SoftAssertionsExtension.class)
class ProfileTest {
@InjectSoftAssertions SoftAssertions softly;
@Test
void profileIsComplete() {
softly.assertThat(profile.email()).isNotBlank();
softly.assertThat(profile.phone()).startsWith("+380");
// the extension calls assertAll() after the test
}
}
Limits and alternatives.
- Soft assertions are wrong when the next step depends on the previous one: there is no point checking the fields of an object if the object itself is
null. Put a hard check first, and soft ones for independent fields. - Do not turn a test into a long list of fields: one scenario checks one behaviour. Soft assertions save reruns but do not replace several tests.
- JUnit 5/6 has its own
Assertionsclass, TestNG hasAssert, and Hamcrest hasassertThat(actual, is(expected)). REST Assured uses Hamcrest matchers, which is why you see them inbody("id", notNullValue()). In new code, values are usually extracted into a POJO and checked through AssertJ. usingRecursiveComparisoncompares deeply and is slower thanisEqualTowith a properequalson large object graphs. Records (record) already haveequals.
Typical mistakes.
new SoftAssertions()withoutassertAll(): the test is green though the fields are wrong. The most insidious mistake of this lesson.assertThat(x.equals(y)).isTrue()instead ofassertThat(x).isEqualTo(y): the report with both values is lost.- Comparing objects with a generated id or time without
ignoringFields: the test always fails. - Checking a collection through
get(0)when the order is not guaranteed: usecontainsExactlyInAnyOrder. - Catching an exception with
try/catchwithoutfail(): if no exception occurs, the test passes.
Check yourself
Why is assertThat(list.contains(x)).isTrue() worse than assertThat(list).contains(x)?
Answer
The first turns the check into a boolean, and on failure the report only says "expected true". The second knows both the list and the wanted element and prints both values.
What happens if you create SoftAssertions by hand and never call assertAll()?
Answer
Failures only pile up in a list but nobody throws them, so the test ends green. Use assertSoftly or SoftAssertionsExtension: they call assertAll themselves.
When do soft assertions do harm?
Answer
When the next check depends on the previous one: after a null object the remaining checks give noise or a NullPointerException. First a hard check of the precondition, then soft ones for independent fields.
assertThat(actual), then a chain of methods the IDE suggests, and a clear failure message with the expected and actual value. Soft assertions collect all failures and show them together, but you need assertAll() or assertSoftly. Middle/Senior: For complex objects I use usingRecursiveComparison with ignoringFields, for collections extracting and containsExactlyInAnyOrder. I use soft assertions only for independent fields and through a JUnit extension, so I cannot forget assertAll. One test checks one behaviour, so a long list of fields is no reason to pile everything into one test.