Skip to content
javahacks.dev
JUnit

How to Use assertThrows and assertAll Properly in JUnit

Use assertThrows to check the exception type and message, and assertAll to see every failure at once, with the mistakes that make both pass by accident.

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

Two of JUnit 5's assertions do work that older tests did with try/catch blocks and a pile of separate asserts: assertThrows checks that code fails the way it should, and assertAll checks several things without stopping at the first mistake. Both are easy to use and easy to use badly, in ways that make a test pass for the wrong reason. This post shows the right use of each, the traps, and when to prefer a different assertion style. It uses JUnit 5 and 6, where the API is the same.

assertThrows: type, message and cause

java
@Test
void rejectsNegativeQuantity() {
    var exception = assertThrows(IllegalArgumentException.class,
            () -> new OrderLine("SKU-1", -1));

    assertEquals("quantity must be positive: -1", exception.getMessage());
}

assertThrows runs the lambda and passes if it throws the given type, and it returns the exception so you can check more about it. The returned value is the reason to prefer it over the old @Test(expected = ...) style, which could not check the message. Assert the message, or part of it, because a test that checks only the type passes when a different line of the same method throws the same exception for a different reason.

Subclasses pass

java
assertThrows(RuntimeException.class, () -> service.charge(null));   // passes for any RuntimeException
assertThrowsExactly(IllegalStateException.class, () -> service.charge(null));

assertThrows accepts the type or any subclass, so asserting Exception.class or RuntimeException.class passes for nearly everything, including a NullPointerException caused by a bug in the test setup. Name the most specific type you expect. When the exact class matters, use assertThrowsExactly, which rejects subclasses.

Keep the lambda small

java
// weak: the exception could come from the setup
assertThrows(OrderException.class, () -> {
    Order order = new Order(customerId);
    order.add(new OrderLine("SKU-1", 1));
    order.pay(Money.of("5", "EUR"));
});

// strong: only the call under test is inside
Order order = new Order(customerId);
order.add(new OrderLine("SKU-1", 1));

assertThrows(OrderException.class, () -> order.pay(Money.of("5", "EUR")));

If the lambda holds the whole scenario, the assertion passes whenever any statement throws the expected type, and a mistake in building the order passes the test as well. Do the setup outside, so that only the one call that should fail is inside. A good test of a failure has a successful setup and a failing call, and you can see the boundary.

Check the cause

Exceptions often wrap others. When the code translates a low-level exception into a domain one, check the original is preserved:

java
var e = assertThrows(GatewayException.class, () -> gateway.charge(request));

assertInstanceOf(SocketTimeoutException.class, e.getCause());

Without that check, a refactoring that drops the cause passes every test and loses the evidence you need in production. The same applies to custom fields on the exception, such as an error code: assert them, since they are part of the contract with the caller.

assertAll: see everything that is wrong

A normal test stops at the first failed assertion. If an object has five wrong fields, you fix one, run again, and learn about the second. assertAll runs every assertion and reports all the failures together:

java
@Test
void mapsTheCustomer() {
    CustomerView view = mapper.toView(customer);

    assertAll("customer view",
            () -> assertEquals("Ada", view.name()),
            () -> assertEquals("[email protected]", view.email()),
            () -> assertEquals(3, view.orderCount()),
            () -> assertTrue(view.active()));
}

The report lists each failing line under the heading, so one run shows all the differences. It is the right tool for checking many properties of one result. Do not use it to string together unrelated steps, because the later assertions run even when an earlier one shows that the setup was already wrong, and the pile of failures hides the first and most informative one.

Nested and combined

assertAll can nest, to group related checks, and it can contain assertThrows:

java
assertAll("order rules",
        () -> assertThrows(IllegalArgumentException.class, () -> new OrderLine("SKU-1", 0)),
        () -> assertThrows(IllegalArgumentException.class, () -> new OrderLine("", 1)),
        () -> assertAll("valid line",
                () -> assertEquals("SKU-1", valid.sku()),
                () -> assertEquals(2, valid.quantity())));

This checks three rules of one constructor in a single test and tells you which of them is broken. For a table of inputs and expected failures, a parameterised test is cleaner, as in parameterised tests.

The opposite: no exception

java
assertDoesNotThrow(() -> validator.validate(validRequest));

String id = assertDoesNotThrow(() -> repository.save(entity));

assertDoesNotThrow fails with the actual exception if there is one, which gives a readable failure for code that should just work. A version that returns a value lets you use the result. Do not add it to every test; a test that calls the code and then asserts on the outcome already fails when an exception escapes.

Writing the failure test first

A good habit is to write the failing case before the code that fails. State the rule in a test, watch it fail because no exception is thrown, then add the validation that throws. The test then proves that it can fail, which a test written after the fact cannot. With assertThrows that is easy to forget, because the test also passes if the code throws the right exception for the wrong reason, such as a NullPointerException inside the constructor. Asserting the message guards against that, and so does running the test once with the validation deleted.

What a good failure test checks

Think of an exception as part of a method's contract. Callers rely on its type to decide what to do, on its message to show or log something useful, and on its fields to build a response. A test that checks all three documents the contract and keeps refactorings honest. Consider a payment that fails with a decline code:

java
var e = assertThrows(PaymentDeclined.class, () -> gateway.charge(card, amount));

assertAll("decline details",
        () -> assertEquals("insufficient_funds", e.code()),
        () -> assertTrue(e.getMessage().contains("insufficient")),
        () -> assertEquals(amount, e.amount()));

The combination of assertThrows returning the exception and assertAll checking it is the idiom to remember. It reads as a specification of the failure. If the team prefers messages not to be asserted verbatim, because they are copy that product people edit, assert on the stable code or the type and check the message only for a fragment.

Timeouts and exceptions in other threads

assertThrows only sees exceptions thrown on the calling thread. An exception in a task submitted to an executor never reaches it. Get the future and assert on ExecutionException, with the cause as the real error:

java
var future = executor.submit(() -> service.slowCall());
var e = assertThrows(ExecutionException.class, () -> future.get(2, TimeUnit.SECONDS));
assertInstanceOf(IllegalStateException.class, e.getCause());

For code that should finish quickly, assertTimeout(Duration.ofSeconds(1), () -> ...) fails if it takes too long, and assertTimeoutPreemptively abandons it, with the thread caveats described in JUnit timeouts.

Messages that help at three in the morning

Both assertions accept a message or a supplier as a last argument. Use the supplier form for messages that are expensive to build, since it is evaluated only on failure: assertEquals(expected, actual, () -> "state was " + dump()). A failure message should say what the test was checking in domain words, not repeat the assertion: "order should be marked paid after a successful charge" tells a reader more than "expected true". The heading you pass to assertAll plays the same role for a group.

Where this does not apply

Fluent libraries read well for complicated checks. AssertJ's assertThatThrownBy(() -> ...).isInstanceOf(...).hasMessageContaining(...).hasCauseInstanceOf(...) chains the same checks in one expression, and SoftAssertions does the work of assertAll. Use one style per project. The JUnit API is documented in the [Assertions Javadoc](https://junit.org/junit5/docs/current/api/org.junit.jupiter.api/org/junit/jupiter/api/Assertions.html) and the user guide section on assertions. For writing readable assertions generally, see readable JUnit 5 assertions, and for getting started, the JUnit 5 tutorial.

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.