Practice: JUnit 5
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Most problems in real test suites are small habits, not missing JUnit features: an assertion that cannot fail, money compared wrongly, a shared fixture, ten copies of one test. Each has a standard fix.
Mistake 1: assertions that cannot fail or that lie
Lying assertion is an assertion that fails with a misleading message, such as assertEquals(actual, expected) with the arguments swapped, or assertTrue(a.equals(b)), which hides both values.
Three tests have the same wrong expectation, but only one of their failure messages tells the truth.
Example 1 · Assertions that lie, and their fixes
Runs in: a Maven project with JUnit 5 and AssertJ (shoplite-api: src/test/java/com/shoplite/cart)
package com.shoplite.cart;
import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertTrue;
import java.math.BigDecimal;
import org.junit.jupiter.api.Test;
class LyingAssertionsTest {
// Swapped arguments: the message calls the real result "expected" @Test void swapped() { Cart cart = new Cart(); cart.add("PEN-BLU", new BigDecimal("10.00"), 3);
assertEquals(cart.itemCount(), 4); }
// assertTrue hides both values @Test void hidden() { Cart cart = new Cart(); cart.add("PEN-BLU", new BigDecimal("10.00"), 3);
assertTrue(cart.total().equals(new BigDecimal("40.00"))); }
// Fixed: expected first, specific assertion @Test void honest() { Cart cart = new Cart(); cart.add("PEN-BLU", new BigDecimal("10.00"), 3);
assertEquals(new BigDecimal("40.00"), cart.total(), "3 pens at 10.00"); }}[ERROR] LyingAssertionsTest.swapped expected: <3> but was: <4> [ERROR] LyingAssertionsTest.hidden expected: <true> but was: <false> [ERROR] LyingAssertionsTest.honest 3 pens at 10.00 ==> expected: <40.00> but was: <30.00>
What this code does
- All three tests have the same wrong expectation (4 pens, Rs 40), but only the last message is true and useful: it names the case and shows the real total, 30.00. The first one claims 3 was expected; the second shows no numbers at all.
- In each case the test is wrong, not the cart: 3 pens are 3 items and Rs 30.00. A clear message makes that obvious in seconds.
The fix is simple: put the expected value first (or use AssertJ, where the actual value always comes first), use the most specific assertion, and work out expected values from the rule, not from the code's own output. Review: Core JUnit assertions (opens in a new tab) and Arrange, Act, Assert (opens in a new tab).
Find the bug
Spot the assertion that cannot help
Tap the line whose failure message would mislead or hide the values.
The cart has 3 items, so this fails, but the message is backwards.
Round 1 of 2Mistake 2: money and objects compared wrongly
Three comparisons go wrong again and again. See each one in plain Java, with its fix.
Example 2 · Three wrong ways to compare, in plain Java
import java.math.BigDecimal;
class Coupon { // no equals() final String code; final int percent;
Coupon(String code, int percent) { this.code = code; this.percent = percent; }}
record CouponRecord(String code, int percent) {}
public class WrongComparisonsDemo { public static void main(String[] args) { BigDecimal total = new BigDecimal("499.00").multiply(BigDecimal.valueOf(3));
System.out.println("1. equals with another scale: " + new BigDecimal("1497").equals(total)); System.out.println(" compareTo == 0 : " + (new BigDecimal("1497").compareTo(total) == 0));
double gstOnFee = new BigDecimal("1199.99").multiply(new BigDecimal("0.18")).doubleValue(); System.out.println("2. money as double : " + gstOnFee + " == 215.9982 ? " + (gstOnFee == 215.9982)); BigDecimal gstExact = new BigDecimal("1199.99").multiply(new BigDecimal("0.18")); System.out.println(" money as BigDecimal : " + gstExact);
System.out.println("3. class without equals : " + new Coupon("FEST20", 20).equals(new Coupon("FEST20", 20))); System.out.println(" record : " + new CouponRecord("FEST20", 20).equals(new CouponRecord("FEST20", 20))); }}1. equals with another scale: false compareTo == 0 : true 2. money as double : 215.9982 == 215.9982 ? true money as BigDecimal : 215.9982 3. class without equals : false record : true
What this code does
- Case 1 is the classic false failure: same amount, different scale. Case 3 is the other classic: two coupons with the same code are "different" until the class gets
equals(), which a record provides. - Case 2 happens to compare equal here, but only by luck of this value; once money becomes a
double, every later sum can carry rounding errors. Keep amounts asBigDecimalall the way into the assertion.
The three are BigDecimal compared with equals and a different scale (2.5 against 2.50), money turned into double before comparing (doubleValue() brings rounding back), and objects of a class without equals() compared with assertEquals.
For money, compare BigDecimal with the same scale or with compareTo or isEqualByComparingTo. For your own classes, add equals() and hashCode() (or use a record) first. Review: Core JUnit assertions (opens in a new tab).
Mistake 3: fixtures that leak between tests
Leaking fixture is test data that survives from one test into the next, such as a static cart, or a list filled in @BeforeAll and then changed by a test.
A leaking fixture is built once and changed by the first test, so the second test sees the leftovers.
Example 3 · A leaking fixture and the fixed version
Runs in: a Maven project with JUnit 5 and AssertJ (shoplite-api: src/test/java/com/shoplite/cart)
package com.shoplite.cart;
import static org.assertj.core.api.Assertions.assertThat;
import java.math.BigDecimal;
import org.junit.jupiter.api.BeforeAll;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.MethodOrderer;import org.junit.jupiter.api.Nested;import org.junit.jupiter.api.Test;import org.junit.jupiter.api.TestMethodOrder;
class FixturesTest {
@Nested @TestMethodOrder(MethodOrderer.MethodName.class) // makes the leak show on every run class Leaking { static Cart cart; // shared and changed by tests
@BeforeAll static void createOnce() { cart = new Cart(); cart.add("NB-A5", new BigDecimal("60.00"), 1); }
@Test void addingPensMakesTwoLines() { cart.add("PEN-BLU", new BigDecimal("10.00"), 2); assertThat(cart.lines()).hasSize(2); }
@Test void totalIsSixty() { assertThat(cart.total()).isEqualByComparingTo("60.00"); } }
@Nested class Fixed { private Cart cart; // fresh for every test
@BeforeEach void createForEachTest() { cart = new Cart(); cart.add("NB-A5", new BigDecimal("60.00"), 1); }
@Test void addingPensMakesTwoLines() { cart.add("PEN-BLU", new BigDecimal("10.00"), 2); assertThat(cart.lines()).hasSize(2); }
@Test void totalIsSixty() { assertThat(cart.total()).isEqualByComparingTo("60.00"); } }}Leaking addingPensMakesTwoLines passed totalIsSixty FAILED expected: 60.00 but was: 80.00 Fixed addingPensMakesTwoLines passed totalIsSixty passed
What this code does
- In
Leaking, the cart is built once in@BeforeAlland changed by the first test, so the second test sees the two pens too.@TestMethodOrderfixes the order so the leak shows on every run; with the opposite order both tests would pass, which is exactly why such bugs hide. (Static members in a@Nestedclass need Java 16 or later; the project uses Java 17.) Fixedbuilds the cart in@BeforeEach, so each test gets its own. The tests are identical; only the fixture moved.
The symptom is always the same: tests pass alone and fail together, or start failing after a rename. Build everything a test may change in @BeforeEach, as instance fields. Keep static and @BeforeAll data read-only, and clean outside resources (files, rows) in @AfterEach. Review: Lifecycle (opens in a new tab).
Mistake 4: copy-pasted tests and hand-made exception checks
Table test is one parameterised test whose rows are the cases. It replaces several copy-pasted tests that differ only in their input and expected value.
Five tests that differ in one number are really one test with a table. Compare the copy-pasted version with the refactored one.
Example 4 · Copy-paste and try/catch, refactored
Runs in: a Maven project with JUnit 5 and AssertJ (shoplite-api: src/test/java/com/shoplite/cart)
package com.shoplite.cart;
import static org.assertj.core.api.Assertions.assertThat;import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.math.BigDecimal;
import org.junit.jupiter.params.ParameterizedTest;import org.junit.jupiter.params.provider.CsvSource;import org.junit.jupiter.params.provider.ValueSource;
class DeliveryAndQuantityTest {
// Before: five @Test methods, one per subtotal, each 4 lines long @ParameterizedTest(name = "subtotal {0} -> delivery {1}") @CsvSource({"0.00, 40.00", "120.00, 40.00", "498.99, 40.00", "499.00, 0.00", "17999.00, 0.00"}) void deliveryCharge(BigDecimal subtotal, BigDecimal expected) { assertThat(DeliveryCharge.forSubtotal(subtotal)).isEqualTo(expected); }
// Before: three try/catch/fail tests for 0, -1 and -100 @ParameterizedTest(name = "quantity {0} is rejected") @ValueSource(ints = {0, -1, -100}) void badQuantities(int quantity) { assertThatThrownBy(() -> new Cart().add("PEN-BLU", new BigDecimal("10.00"), quantity)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Quantity must be at least 1"); }}[INFO] Running com.shoplite.cart.DeliveryAndQuantityTest [INFO] Tests run: 8, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.091 s -- in com.shoplite.cart.DeliveryAndQuantityTest
What this code does
- Eight tests are still reported, one per row, but the code is two short methods. Each table shows every case at a glance, including the boundary rows 498.99 and 499.00.
- The exception test now also checks the message, which the old
try/catchversions skipped, so a differentIllegalArgumentExceptioncannot make it pass.
A @ParameterizedTest with @CsvSource keeps the cases side by side and still reports each row. Exception checks written with try/catch/fail become one assertThrows (or assertThatThrownBy) that also checks the message. Review: Parameterised tests (opens in a new tab) and Exceptions and timeouts (opens in a new tab).
Finish up
Mark complete & continue
Next: Mini project: a test suite for the ShopLite cart