Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Java
Stage 5: Specialization

Part 10 / Topic 5 of 12

Assertions in depth

org.junit.jupiter.api.Assertions is a class of static methods — all of Section 3 and 4's assertEquals calls are static imports from it.

Assertion Checks Notes
assertEquals(expected, actual) expected.equals(actual) fine for int, String, objects with a real equals
assertEquals(expected, actual, delta) within delta of each other use this for double/float — floating-point maths rarely lands on an exact bit pattern
assertTrue(condition) / assertFalse(condition) a boolean prefer a more specific assertion when one exists (assertEquals over assertTrue(a == b))
assertNotNull(obj) / assertNull(obj) reference is/isn't null
assertThrows(Type.class, executable) the lambda throws exactly that type (or a subtype) returns the exception, so you can assert on its message too
assertAll(heading, exec1, exec2, ...) every lambda, even after one fails reports all failures in the group, not just the first

🔍 Going deeper: why assertEquals(1180.0, result, 0.001) and not assertEquals(1180.0, result)? 0.18 + 0.82 in double arithmetic is not always bit-for-bit 1.0 — IEEE 754 binary floating point cannot represent every decimal exactly. assertEquals(double, double) with no delta still exists and works for values that happen to land exactly, but relying on that is fragile; a small tolerance (delta) is the standard fix, the same idea as Python's pytest.approx.

assertThrows and the exception it hands back:

@Test
void finalPrice_negativePrice_throwsIllegalArgumentException() {
    IllegalArgumentException error = assertThrows(
            IllegalArgumentException.class,
            () -> DiscountCalculator.finalPrice(-500.0));
    assertEquals("price cannot be negative: -500.0", error.getMessage());
}

The lambda () -> DiscountCalculator.finalPrice(-500.0) is not run until assertThrows runs it and watches for the exception — this is the same "pass behaviour as a value" idea Part 9 will cover for functional interfaces in full; for now, read it as "the code to run, wrapped so JUnit controls when it runs."

assertAll for a group of related checks on one result:

@Test
void finalPrice_groupedChecksOnOneBill() {
    double result = DiscountCalculator.finalPrice(2000.0, 10.0);
    assertAll("a 2000 bill with 10% off",
            () -> assertEquals(2124.0, result, 0.001),
            () -> assertEquals(true, result > 0, "final price must stay positive"),
            () -> assertEquals(true, result < 2360.0, "final price must be less than the no-discount price"));
}

Without assertAll, a plain sequence of three separate assertEquals calls would stop at the first failure and never tell you about the other two in the same run — assertAll runs every lambda regardless, and reports every failure together.

Readable failure messages

Every assertion above that takes an extra String argument ("800 after discount, then 18% GST should be 944", "final price must stay positive") is a custom failure message — it is only ever shown if the assertion fails, and it costs nothing when it passes. Compare what a failure looks like with and without one: expected: <944.0> but was: <940.0> tells you the two numbers; 800 after discount, then 18% GST should be 944 ==> expected: <944.0> but was: <940.0> tells you what the test believed should be true, which is the part a bare number never carries. Write the message as if you will read it at 11 p.m. with no memory of writing the test.

Reading a real failure

Every green run so far means nothing was proven about reading JUnit's failure output — and that is the output you actually need to understand under pressure. examples/broken-test-demo/ is a separate folder, on purpose: it has its own copy of DiscountCalculator.java next to BrokenTest.java, so this one deliberately failing test never sits inside the all-green suite built up through the rest of this part. BrokenTest.java has one test with a deliberately wrong expected value:

@Test
void finalPrice_withPercentOff_discountsThenAddsGst() {
    double result = DiscountCalculator.finalPrice(1000.0, 20.0);
    assertEquals(940.0, result, 0.001); // wrong: the real answer is 944.0
}
$ javac -cp ../lib/junit-platform-console-standalone-1.14.5.jar DiscountCalculator.java BrokenTest.java
$ java -jar ../lib/junit-platform-console-standalone-1.14.5.jar execute -cp . --scan-class-path --details=tree --disable-ansi-colors

Thanks for using JUnit! Support its development at https://junit.org/sponsoring

╷
├─ JUnit Platform Suite ✔
├─ JUnit Jupiter ✔
│  └─ BrokenTest ✔
│     └─ finalPrice_withPercentOff_discountsThenAddsGst() ✘ expected: <940.0> but was: <944.0>
└─ JUnit Vintage ✔

Failures (1):
  JUnit Jupiter:BrokenTest:finalPrice_withPercentOff_discountsThenAddsGst()
    MethodSource [className = 'BrokenTest', methodName = 'finalPrice_withPercentOff_discountsThenAddsGst', methodParameterTypes = '']
    => org.opentest4j.AssertionFailedError: expected: <940.0> but was: <944.0>
       org.junit.jupiter.api.AssertEquals.assertEquals(AssertEquals.java:81)
       org.junit.jupiter.api.Assertions.assertEquals(Assertions.java:1014)
       BrokenTest.finalPrice_withPercentOff_discountsThenAddsGst(BrokenTest.java:9)
       ...

Test run finished after 20 ms (varies)
[         1 tests failed          ]
$ echo "EXIT:$?"
EXIT:1

Three things to notice, every time a test fails: the ✘ line gives expected vs. was right where the failing test sits in the tree; the stack trace's first BrokenTest.java:9 line (not the JUnit internals above it) is where the assertion actually lived; and the whole process exits with status 1, not 0 — this is exactly what a CI pipeline checks to decide "build broke." Here the bug is in the test (940.0 should be 944.0, see Section 3's DiscountCalculator), not the code — a healthy first reaction to any red test is "which of these two is wrong?", not an assumption that the code is always at fault.

Done here? The practice set for Part 10 — including the solutions — is on the part page.

Search the guide