Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 29 ยท JUnit core

JUnit Assertions in Depth

Master JUnit 6 assertions: equality and delta, assertAll grouping, assertThrows, iterables and arrays, lazy failure messages, plus AssertJ and Hamcrest as alternatives.

An assertion is the part of a test that can say no. Everything before it sets the scene; the assertion decides whether the scene ended the way you promised it would. Because a failing assertion is the only thing a developer reads at 2 a.m. in a CI log, the quality of its message is as important as its correctness.

JUnit's Assertions class has dozens of methods, but a small handful covers nearly every test. This lesson tours them, shows the exact messages they produce (we run real failing tests so you can read them), and finishes with the two popular third-party assertion libraries, AssertJ and Hamcrest. It builds on Your First JUnit Test.

Pick the assertion that explains itself

Equality assertEquals, assertNotEquals, assertSame.
Conditions assertTrue, assertFalse, assertNull.
Collections assertIterableEquals, assertArrayEquals.
Exceptions assertThrows, assertDoesNotThrow.
1 / 2

Equality first

assertEquals(expected, actual) is the workhorse. For objects it calls expected.equals(actual), for primitives it compares values. The expected value goes first, because the failure message prints them in that order:

Java
assertEquals("Hello", greeting);        // expected: <Hello> but was: <Hallo>

Related methods:

  • assertNotEquals(unexpected, actual) passes when the values differ.
  • assertSame(expected, actual) and assertNotSame(...) compare identity (==), not equals. You rarely want this except for singletons and caching tests.
  • assertNull(x) / assertNotNull(x) check for null.
  • assertTrue(condition) / assertFalse(condition) check a boolean. Prefer a specific assertion when one exists: assertTrue(a.equals(b)) fails with only "expected: but was: ", while assertEquals(a, b) shows both values.

Doubles need a tolerance

Binary floating point cannot store 0.1 exactly, so 0.1 + 0.2 is 0.30000000000000004. Pass a third argument, the delta, the largest difference you still accept:

Java
assertEquals(0.3, 0.1 + 0.2, 1e-9);   // passes

Choose the delta from the problem, not the other way around: a currency calculation in cents needs no delta at all if you use long or BigDecimal; a physics simulation may need 1e-6. NaN equals NaN for assertEquals on doubles, which surprises people who know that Double.NaN == Double.NaN is false in plain Java.

Seeing real failure messages

Reading messages is a skill. The example below has five tests, and every one of them fails on purpose. Run it and compare each message with the assertion that produced it.

Java What failure messages look like

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The report shows, for example, expected: <0.3> but was: <0.30000000000000004> for the double test, iterable contents differ at index [1], expected: <2> but was: <5> for the list, and item must be in stock ==> expected: <true> but was: <false> for the last one. (Tests may print in a different order than the source.) Three habits come out of that output:

  • Compare whole values when you can. A record has a generated equals, so one assertEquals on the whole object shows every component. Several separate assertions on x() and y() would hide the second problem behind the first.
  • Use the collection assertions for collections. assertIterableEquals names the index where the contents diverge; assertEquals(list1, list2) also works, but only prints the two lists in full.
  • A custom message is a prefix, not a replacement. JUnit keeps its own expected ... but was ... text and adds yours in front. Use messages to explain intent ("item must be in stock"), not to repeat the values.

Messages that cost nothing

Every assertion has a last parameter for a message, and it comes in two flavors: a plain String or a Supplier<String>. The plain string is built before the assertion runs, even when the test passes. If building it is expensive (formatting a big object, calling a method), use the lambda form, which is only invoked on failure.

Java A lazy message is only built on failure

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Only the eager version called describe, so the counter is 1. For a message like "expected " + order where order.toString() walks a large object graph, that difference adds up across thousands of tests.

Checking several things with assertAll

A normal test stops at the first failing assertion. assertAll takes any number of lambdas, runs all of them, and reports every failure together. Use it to check several properties of one result:

Java
assertAll("invoice",
    () -> assertEquals("INV-7", invoice.number()),
    () -> assertEquals(3, invoice.lines().size()),
    () -> assertEquals(4200, invoice.totalCents()));

When two of the three are wrong, the report says something like invoice (2 failures) and lists both. The heading string is optional but useful. Do not use assertAll to glue unrelated scenarios into one test: if you need to say "and then, separately", write another @Test.

Testing that code throws

assertThrows(Type.class, executable) passes when the lambda throws that type or a subclass. It returns the exception so you can inspect it:

Java
IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
        () -> Discounts.apply(1000, 120));
assertEquals("percent must be 0-100, was 120", e.getMessage());

Variations worth knowing:

  • assertThrowsExactly(Type.class, ...) rejects subclasses. Use it when the precise type is part of your contract.
  • assertDoesNotThrow(() -> ...) passes when nothing is thrown, and returns the value of a ThrowingSupplier. It documents the intent "this must not blow up" better than an empty test.
  • fail("message") fails immediately. It is rarely needed; reach for assertThrows instead of try { ...; fail(); } catch (...) {}.

Keep only the single throwing call inside assertThrows. If you also build objects inside the lambda and one of those lines throws the same exception type, the test passes for the wrong reason.

Java assertAll, assertThrows and the returned exception

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

All five pass. Try breaking one number in totalsAndSkus to watch assertAll list the failure under the invoice heading.

Arrays and iterables

Arrays do not override equals, so assertEquals(new int[]{1,2}, new int[]{1,2}) fails, because it compares identity. Use assertArrayEquals(expected, actual), which compares length and elements (and nested arrays). For List, Set in iteration order, and any other Iterable, use assertIterableEquals. For output captured as lines of text, assertLinesMatch(expectedLines, actualLines) also accepts regular expressions and >> skipped lines >> markers, which helps with logs that contain timestamps.

Sets and maps have no guaranteed order for some implementations. Compare them with assertEquals(Set.of(...), actualSet), which uses Set.equals, rather than iterating.

Type checks and returned values

assertInstanceOf(Dog.class, animal) passes if animal is a Dog and returns it already cast, saving a separate cast line. Many JUnit assertions return something useful (assertThrows, assertDoesNotThrow, assertInstanceOf), which keeps tests short.

Third-party assertion libraries (read-only)

JUnit's assertions are intentionally plain. Two libraries add richer vocabulary. They are not on this site's runner, so these are real, read-only snippets.

AssertJ offers a fluent API that reads like a sentence, with autocompletion that offers only the checks that make sense for the type:

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

assertThat(names)
    .hasSize(3)
    .contains("Ada", "Alan")
    .doesNotContain("Bob");

assertThat(order.status()).isEqualTo(Status.SHIPPED);
assertThat(price).isCloseTo(9.99, within(0.001));

Hamcrest uses matcher objects, which compose with not, allOf and anyOf:

Java
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;

assertThat(names, hasSize(3));
assertThat(names, hasItems("Ada", "Alan"));
assertThat(score, is(greaterThan(90)));

Neither is required. Plain JUnit assertions cover most needs, and many teams add AssertJ only when they have complex collection or object checks. Whichever you choose, use one style per project so tests look alike.

Common mistakes

  • Swapped arguments. The test still passes or fails correctly, but the message lies about which value is expected.
  • Exact double comparison. Always pass a delta, or avoid floating point for values that must be exact.
  • assertEquals on arrays. It compares identity, so it fails for equal arrays. Use assertArrayEquals.
  • assertTrue(x.equals(y)). The failure message loses both values. Use assertEquals.
  • Empty catch blocks. try { call(); } catch (Exception e) {} swallows the failure. Let the exception escape or use assertThrows.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does assertEquals(new int[]{1, 2}, new int[]{1, 2}) do?

    Arrays do not override equals, so assertEquals compares references and the call fails. Use assertArrayEquals for element-by-element comparison.
  2. 2. Why prefer the lambda form () -> "state: " + obj for an assertion message?

    A Supplier is called lazily. A plain String is built before the assertion runs, even when the test passes, which wastes time if building it is expensive.
  3. 3. A test uses assertAll with three lambdas and two of them fail. What does the report contain?

    assertAll runs every grouped assertion and reports all failures together in a MultipleFailuresError.
  4. 4. Which assertion would you use to require that the code throws exactly IllegalStateException, not a subclass?

    assertThrows accepts subclasses. assertThrowsExactly insists on the precise type.
  5. 5. What is the third argument in assertEquals(0.3, 0.1 + 0.2, 1e-9)?

    For floating point values the third argument is a tolerance. The check passes when the two numbers differ by no more than that amount.

Summary

  • assertEquals(expected, actual) is the default; use assertSame only for identity, and give doubles a delta.
  • Compare whole values (records, lists, arrays) with the matching assertion so failure messages show everything.
  • Custom messages are prefixes; use a Supplier when building the message is expensive.
  • assertAll runs every grouped check and reports all failures together; assertThrows returns the exception for further checks.
  • Arrays need assertArrayEquals, iterables assertIterableEquals.
  • AssertJ and Hamcrest add fluent or matcher-based styles; they are optional and shown here read-only.

Next: Lifecycle, Nested Tests and Display Names, where you share setup code and group tests so they read like a specification.