Unit Testing with JUnit 5

November 27, 202612 minutes

Part 1 of 5

Stop reading printed output. Learn to set up JUnit 5, write tests that pass or fail on their own, test boundaries with a parameterized test, and avoid the pitfalls that make a green test lie.

Your team checks the shipping calculator by printing results in main and reading them. Run it, and it prints 0.0, then 7.99. Both look right, so everyone moves on. Next week, someone edits one comparison: an order of exactly a hundred dollars now pays for shipping. But nobody printed a hundred, so nobody notices.

public static void main(String[] args) {
    ShippingCalculator calc = new ShippingCalculator();
    System.out.println(calc.cost(new Order(120, false)));
    System.out.println(calc.cost(new Order(50, false)));
}

Prefer to watch? The narrated video covers the same lesson (about ten minutes). The article follows it section by section, with diagrams, the Maven equivalent and a little extra depth.

This is lesson zero of a series on testing in Java. Next come code coverage with JaCoCo (which code your tests ran) and mutation testing with PIT (whether anything would notice a planted bug). After those, Mockito (test doubles) and test-driven development (writing the test first) round out the series. Every lesson reuses the same small calculator.

Reading the output doesn’t scale

Reading output by eye has two problems. It checks only what you remember to print, and only on the days you look. A real check runs by itself, every time, and says pass or fail. That is a unit test, and in Java the standard tool is JUnit 5. A unit test checks one small piece of code, like a method, on its own and in milliseconds, with no network and no database.

The code under test

An order has a total and an express flag. The cost method returns zero when the total is at least a hundred, and the flat rate otherwise. Express orders add fifteen on top.

public record Order(double total, boolean express) {}
public double cost(Order order) {
    double shipping;
    if (order.total() >= 100) {
        shipping = 0;
    } else {
        shipping = 7.99;
    }
    if (order.express()) {
        shipping += 15;
    }
    return shipping;
}

It is small, but it has a boundary at 100 and two decisions, which is exactly what tests are for.

A pilot’s pre-flight checklist

Before every flight, a pilot runs the same checklist. Each item says what to check and what the answer must be. Nobody skips it because the plane feels fine: it runs before every flight, not only when something seems wrong.

A test suite is that checklist. Each test is one item. An assertion is the reading that says pass or fail. And the build runs the whole list before a change ships. When an item fails, the plane stays on the ground while the fix is still cheap.

The pre-flight checklist mapped onto testing: a checklist item is a test, the reading that says pass or fail is an assertion, the flight clearance is a green build, and a plane held on the ground is a failed build. The pre-flight checklist mapped onto testing: a checklist item is a test, the reading that says pass or fail is an assertion, the flight clearance is a green build, and a plane held on the ground is a failed build.
The checklist, mapped onto the lesson.

Setup

To run tests with Gradle, add the Jupiter dependency, and the platform launcher at runtime. The JUnit bill of materials (BOM) keeps every version in step. Then tell the test task to use the JUnit platform.

dependencies {
    testImplementation(platform("org.junit:junit-bom:5.14.4"))
    testImplementation("org.junit.jupiter:junit-jupiter")
    testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}

tasks.test {
    useJUnitPlatform()
}

Tests live under src/test/java, and gradle test finds and runs every one. A complete build.gradle.kts for the example project:

plugins {
    java
}

repositories {
    mavenCentral()
}

dependencies {
    testImplementation(platform("org.junit:junit-bom:5.14.4"))
    testImplementation("org.junit.jupiter:junit-jupiter")
    testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}

tasks.test {
    useJUnitPlatform()
}

In Maven, add the same Jupiter dependency with test scope. The JUnit guide recommends a recent Surefire plugin (3.0.0 or later):

<dependencies>
  <dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter</artifactId>
    <version>5.14.4</version>
    <scope>test</scope>
  </dependency>
</dependencies>

<build>
  <plugins>
    <plugin>
      <artifactId>maven-surefire-plugin</artifactId>
      <version>3.5.3</version>
    </plugin>
  </plugins>
</build>

A note on versions: this lesson uses JUnit 5.14.4, the last 5.x release. JUnit 6 now exists, and the JUnit site shows it as current. JUnit 5 itself runs on Java 8 or later, and the course uses Java 17 or later. The annotations and assertions in this lesson are the same ones you will meet in JUnit 6.

The first test: arrange, act, assert

A test is a method marked with the @Test annotation. It doesn’t have to be public, but it can’t be private, and it returns nothing. Import the assertions statically so you can write assertEquals on its own.

Write the test in three steps. Arrange: build the calculator and the order. Act: call cost. Assert: compare the result with what you expect.

class ShippingCalculatorTest {
    @Test
    void largeOrderShipsFree() {
        // arrange
        ShippingCalculator calc = new ShippingCalculator();
        Order order = new Order(120, false);
        // act
        double cost = calc.cost(order);
        // assert
        assertEquals(0.0, cost);
    }
}
The three steps of a test in order: arrange builds the calculator and the order, act calls cost, assert compares the result with the expected value. The three steps of a test in order: arrange builds the calculator and the order, act calls cost, assert compares the result with the expected value.
Three steps.

assertEquals takes the expected value first, then the actual one. Mix them up and the test still passes or fails correctly, but the failure message reads backwards. When a test fails, JUnit prints both values, for example expected: <0.0> but was: <7.99>, so you can see the difference without a debugger.

Money in a double needs one more habit. In floating point, 7.99 plus 15 is not exactly 22.99: in a Java double it is 22.990000000000002. So give assertEquals a delta, a small tolerance:

class ShippingCalculatorTest {
    @Test
    void largeOrderShipsFree() {
        ShippingCalculator calc = new ShippingCalculator();
        Order order = new Order(120, false);
        double cost = calc.cost(order);
        assertEquals(0.0, cost);
    }

    @Test
    void expressAddsFifteen() {
        ShippingCalculator calc = new ShippingCalculator();
        double cost = calc.cost(new Order(50, true));
        assertEquals(22.99, cost, 0.001);
    }
}

Run the tests with gradle test, and each one reports pass or fail. Nothing to read, and nothing to remember. A red build is a failed item on the checklist.

A fresh start for every test

Both tests build their own calculator. Move that into a method marked @BeforeEach, and JUnit runs it before every single test. @DisplayName lets you name a test with a sentence, spaces and all; reports and the IDE show that sentence instead of the method name.

class ShippingCalculatorTest {
    private ShippingCalculator calc;

    @BeforeEach
    void setUp() {
        calc = new ShippingCalculator();
    }

    @Test
    @DisplayName("an order of 120 ships free")
    void largeOrderShipsFree() {
        assertEquals(0.0, calc.cost(new Order(120, false)));
    }
}

JUnit also creates a new instance of the test class for every test method. So fields start fresh, and one test can’t leave a mess for the next.

Sequence of a run: JUnit creates a new instance of the test class for the first test, runs the BeforeEach method and the first test on it, then creates a second new instance for the second test and repeats. Sequence of a run: JUnit creates a new instance of the test class for the first test, runs the BeforeEach method and the first test on it, then creates a second new instance for the second test and repeats.
One instance per test method.

Errors and grouped checks

Some behaviour is an error. Say an order with a negative total must be rejected. The order itself checks, and throws an IllegalArgumentException. (A record’s compact constructor is a natural place for this kind of check.)

public record Order(double total, boolean express) {
    public Order {
        if (total < 0) {
            throw new IllegalArgumentException("total must not be negative");
        }
    }
}

assertThrows takes the exception type and a lambda. It runs the lambda and checks that it throws that type (or a subtype). It also returns the exception, so you can check the message.

@Test
void negativeTotalIsRejected() {
    IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
            () -> new Order(-5, false));
    assertEquals("total must not be negative", e.getMessage());
}

Sometimes one behaviour needs several checks. assertAll runs every check, and reports all the failures together, not just the first.

@Test
void expressAddsFifteenEverywhere() {
    assertAll(
        () -> assertEquals(15.0, calc.cost(new Order(100, true)), 0.001),
        () -> assertEquals(22.99, calc.cost(new Order(50, true)), 0.001)
    );
}
Which assertion to reach for: to compare a value use assertEquals, with a delta for doubles; to check an error use assertThrows; to check several things about one behaviour use assertAll; to check a plain condition use assertTrue. Which assertion to reach for: to compare a value use assertEquals, with a delta for doubles; to check an error use assertThrows; to check several things about one behaviour use assertAll; to check a plain condition use assertTrue.
Which assertion fits.

Boundaries with a parameterized test

Boundaries need many inputs and the same check. A @ParameterizedTest runs one method once for every row you give it. Each @CsvSource string is one row of arguments, and the method takes one parameter for each column. JUnit converts the text to double and boolean for you.

@ParameterizedTest
@CsvSource({
    "99.99, false, 7.99",
    "100, false, 0",
    "100.01, false, 0",
    "100, true, 15"
})
void costAroundTheBoundary(double total, boolean express, double expected) {
    assertEquals(expected, calc.cost(new Order(total, express)), 0.001);
}

Just under a hundred pays the flat rate (99.99 gives 7.99). Exactly a hundred, and just over, ship free. And express adds fifteen to a free order.

RowTotalExpressExpected cost
199.99false7.99
2100false0
3100.01false0
4100true15

@ParameterizedTest needs the junit-jupiter-params artifact, which the junit-jupiter dependency already includes. For a bigger suite, nested classes group tests by topic. Mark a non-static inner class with @Nested; the outer class’s @BeforeEach runs before the inner tests.

class ShippingCalculatorTest {
    private ShippingCalculator calc;

    @BeforeEach
    void setUp() {
        calc = new ShippingCalculator();
    }

    @Nested
    class ExpressOrders {
        @Test
        void addFifteen() {
            assertEquals(22.99, calc.cost(new Order(50, true)), 0.001);
        }
    }
}

The bug, caught

Now replay the bad edit from the start of the lesson: >= becomes a plain >, and we run the tests. Two rows fail. The row for exactly a hundred expected zero, and the calculator returned 7.99. (The row for an express order at a hundred fails too, because the flat rate is now added on top of the express fee.) Change the comparison back, and every row goes green again.

RowResult after the editMessage
99.99, falsepass
100, falsefailexpected: <0.0> but was: <7.99>
100.01, falsepass
100, truefailexpected: <15.0> but was: <22.990000000000002>

(This is a simplified view of a test report, worked out by hand from the code.) The boundary test notices what printing never did. And it keeps noticing, on every build, long after anyone remembers this edit.

Best practices

  1. One behaviour per test. When it fails, its name tells you what broke, and you don’t have to debug to find out. A test that checks five things fails for five reasons. (assertAll is fine when the checks describe the same behaviour.)
  2. Name tests for the behaviour. largeOrderShipsFree tells you more than test1, and reads well in a failure report. Say what happens, and under which condition.
  3. No logic in tests. A loop that recomputes the expected value repeats the production rule, and its bug. Write the expected value as a plain number, worked out by hand.
for (double total = 100; total < 105; total++) {
    double expected = total >= 100 ? 0 : 7.99;
    assertEquals(expected, calc.cost(new Order(total, false)), 0.001);
}
  1. Independent tests. Each one must pass alone, or in any order, and starts from a fresh state. If test two needs test one to run first, they are one test pretending to be two.
  2. Test public behaviour, not private methods. If a private method seems to need its own test, it may want to be its own class. Tests that reach into internals break whenever you refactor.
  3. Boundaries first. Bugs gather at the edges: just under, exactly on, and just over. Our hook bug lived at exactly a hundred.

Pitfalls: when the check lies

  1. Swapped arguments. Put the actual value first, and a failing test says it expected 7.99 and got 0, exactly backwards. (Here the order is exactly a hundred, after the bad edit.)
assertEquals(cost, 0.0);

The failure reads expected: <7.99> but was: <0.0>, but the truth is the reverse. Write assertEquals(0.0, cost);. 2. assertTrue(a == b). When it fails, the message only says expected: <true> but was: <false>. It never shows the two values. assertEquals does.

assertTrue(cost == 0.0);
  1. Exact equality on doubles. The value 22.99 fails against the computed result, which has a tiny extra tail (but was: <22.990000000000002>). Pass a delta.
assertEquals(22.99, calc.cost(new Order(50, true)));
  1. A test with no assertion. It passes whatever cost returns. And the coverage report still counts its lines as covered, as the JaCoCo lesson shows. A green build needs assertions that can fail.
calc.cost(new Order(120, true));

Pitfalls: when tests interfere

  1. Shared mutable state. If one test fills a static list and another reads it, the result depends on which ran first. JUnit’s default order is deterministic but intentionally non-obvious, so never rely on it. (Instance fields are safe, because each test gets a new instance. static fields are not.)
private static final List<Order> orders = new ArrayList<>();
  1. Depending on the clock. A test that reads today’s date passes today and fails on another day. Pass a Clock into the code, and use a fixed clock (Clock.fixed(...)) in the test.
LocalDate today = LocalDate.now();
LocalDate today = LocalDate.now(clock);
  1. Catching exceptions inside a test. If nothing is thrown, the catch block never runs and the test still passes. Use assertThrows instead.
try {
    new Order(-5, false);
} catch (IllegalArgumentException e) {
    // expected
}

Put the pitfalls together, and a good test has one reason to fail. It passes alone, in any order, on any day, and tells you what broke when it doesn’t.

The whole test class

All the pieces together:

import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;

class ShippingCalculatorTest {
    private ShippingCalculator calc;

    @BeforeEach
    void setUp() {
        calc = new ShippingCalculator();
    }

    @Test
    @DisplayName("an order of 120 ships free")
    void largeOrderShipsFree() {
        assertEquals(0.0, calc.cost(new Order(120, false)));
    }

    @Test
    void negativeTotalIsRejected() {
        IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
                () -> new Order(-5, false));
        assertEquals("total must not be negative", e.getMessage());
    }

    @Test
    void expressAddsFifteenEverywhere() {
        assertAll(
            () -> assertEquals(15.0, calc.cost(new Order(100, true)), 0.001),
            () -> assertEquals(22.99, calc.cost(new Order(50, true)), 0.001)
        );
    }

    @ParameterizedTest
    @CsvSource({
        "99.99, false, 7.99",
        "100, false, 0",
        "100.01, false, 0",
        "100, true, 15"
    })
    void costAroundTheBoundary(double total, boolean express, double expected) {
        assertEquals(expected, calc.cost(new Order(total, express)), 0.001);
    }
}

Common questions

“How many tests do I need?” Enough that every decision and every boundary in the code has one. The next two lessons give you tools to measure that: coverage shows which code ran, and mutation testing shows whether anything would notice a change.

“Should I test getters and setters?” Usually not on their own. They are exercised by the tests of the behaviour that uses them.

“JUnit 4 or JUnit 5?” This course uses JUnit 5 (Jupiter). JUnit 4’s org.junit.Test and the Jupiter org.junit.jupiter.api.Test are different annotations, so don’t mix the imports in one class.

Recap

Mark a method with @Test. Arrange, act, assert. assertEquals takes the expected value first, with a delta for doubles. Use @BeforeEach for a fresh start, assertThrows for errors, and a parameterized test for boundaries. Then run the whole list on every build.

Don’t read the output. Assert it.

This is the first lesson of a series, and every lesson reuses this same calculator. Next: JaCoCo shows which code your tests ran, and PIT asks whether anything would notice a planted bug. Mockito replaces slow collaborators, and test-driven development writes the test first.

The five lessons of the testing series in order: JUnit 5 unit testing, JaCoCo coverage, PIT mutation testing, Mockito test doubles, and test-driven development. The five lessons of the testing series in order: JUnit 5 unit testing, JaCoCo coverage, PIT mutation testing, Mockito test doubles, and test-driven development.
The testing series: write the check, see what ran, see what was checked, replace collaborators, write the test first.

References