QA Interview Hub · Knowledge base · Quizzes · Українська

Java Core › Assertions and API tests

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 a false).
  • extracting pulls 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 no equals. Generated fields (id, creation time) are excluded through ignoringFields.
  • assertThatThrownBy checks the type and text of an exception. It is handier than try/catch with a manual fail().

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

Hard

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.

Soft

Collects all

All failures in one report from a single run. Fits independent fields of one object.

Figure 1. These are two legitimate choices, not "bad" and "good": the difference is whether the next check depends on the previous one.

The life of a soft assertion

softly.assertThat(...)no throw, the failure is rememberedthe next checks run toothe list of failures growsassertAll()one AssertionError with all failures
Figure 2. Without the last step the failures go nowhere and the test passes.
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 Assertions class, TestNG has Assert, and Hamcrest has assertThat(actual, is(expected)). REST Assured uses Hamcrest matchers, which is why you see them in body("id", notNullValue()). In new code, values are usually extracted into a POJO and checked through AssertJ.
  • usingRecursiveComparison compares deeply and is slower than isEqualTo with a proper equals on large object graphs. Records (record) already have equals.

Typical mistakes.

  • new SoftAssertions() without assertAll(): the test is green though the fields are wrong. The most insidious mistake of this lesson.
  • assertThat(x.equals(y)).isTrue() instead of assertThat(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: use containsExactlyInAnyOrder.
  • Catching an exception with try/catch without fail(): 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.

In the interview. Junior: AssertJ is fluent assertions: 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.

More articles in this chapter