# Unit Testing with JUnit 5Stop 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.

```java
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.

{{< lesson-video youtube="aQgWWD8kO4g" title="Unit Testing with JUnit 5" >}}

This is lesson zero of a series on testing in Java. Next come
[code coverage with JaCoCo](/testing/jacoco-code-coverage/) (which code your tests ran) and
[mutation testing with PIT](/testing/pit-mutation-testing/) (whether anything would notice a
planted bug). After those, [Mockito](/testing/mockito-test-doubles/) (test doubles) and [test-driven development](/testing/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.

```java
public record Order(double total, boolean express) {}
```

```java
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.

```mermaid {alt="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." caption="The checklist, mapped onto the lesson."}
flowchart LR
  A1["checklist item"] --> B1["a test"]
  A2["the reading: pass or fail"] --> B2["an assertion"]
  A3["flight clearance"] --> B3["a green build"]
  A4["plane stays on the ground"] --> B4["a failed build"]
  class A1,A2,A3 c4
  class B1,B2 c1
  class A4 hl
  class B3 good
  class B4 bad
```

## 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.

```kotlin
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:

```kotlin
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):

```xml
<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.

```java
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);
    }
}
```

```mermaid {alt="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." caption="Three steps."}
flowchart LR
  A["arrange<br/>build the calculator<br/>and the order"] --> B["act<br/>call cost"]
  B --> C["assert<br/>compare with<br/>the expected value"]
  class A c5
  class B c1
  class C good
```

`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:

```java
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.

```java
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.

```mermaid {alt="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." caption="One instance per test method."}
sequenceDiagram
  participant J as JUnit
  participant A as instance for test 1
  participant B as instance for test 2
  J->>A: new, then @BeforeEach
  J->>A: run test 1
  J->>B: new, then @BeforeEach
  J->>B: run test 2
```

## 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.)

```java
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.

```java
@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.

```java
@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)
    );
}
```

```mermaid {alt="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." caption="Which assertion fits."}
flowchart TD
  Q["what do you check?"] --> V["a value"]
  Q --> E["an error"]
  Q --> M["several things,<br/>one behaviour"]
  Q --> C["a plain condition"]
  V --> V1["assertEquals<br/>(delta for doubles)"]
  E --> E1["assertThrows"]
  M --> M1["assertAll"]
  C --> C1["assertTrue"]
  class Q hl
  class V1,E1,M1,C1 good
```

## 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.

```java
@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.

| Row | Total | Express | Expected cost |
|---|---|---|---|
| 1 | 99.99 | false | 7.99 |
| 2 | 100 | false | 0 |
| 3 | 100.01 | false | 0 |
| 4 | 100 | true | 15 |

`@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.

```java
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.

| Row | Result after the edit | Message |
|---|---|---|
| 99.99, false | pass | |
| 100, false | **fail** | `expected: <0.0> but was: <7.99>` |
| 100.01, false | pass | |
| 100, true | **fail** | `expected: <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.

```java
for (double total = 100; total < 105; total++) {
    double expected = total >= 100 ? 0 : 7.99;
    assertEquals(expected, calc.cost(new Order(total, false)), 0.001);
}
```

4. **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.
5. **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.
6. **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.)

```java
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.

```java
assertTrue(cost == 0.0);
```

3. **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.

```java
assertEquals(22.99, calc.cost(new Order(50, true)));
```

4. **A test with no assertion.** It passes whatever `cost` returns. And the coverage report still
   counts its lines as covered, as the [JaCoCo lesson](/testing/jacoco-code-coverage/) shows. A
   green build needs assertions that can fail.

```java
calc.cost(new Order(120, true));
```

## Pitfalls: when tests interfere

5. **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.)

```java
private static final List<Order> orders = new ArrayList<>();
```

6. **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.

```java
LocalDate today = LocalDate.now();
```

```java
LocalDate today = LocalDate.now(clock);
```

7. **Catching exceptions inside a test.** If nothing is thrown, the `catch` block never runs and the
   test still passes. Use `assertThrows` instead.

```java
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:

```java
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](/testing/jacoco-code-coverage/) shows which code your tests ran, and
[PIT](/testing/pit-mutation-testing/) asks whether anything would notice a planted bug. [Mockito](/testing/mockito-test-doubles/)
replaces slow collaborators, and [test-driven development](/testing/test-driven-development/) writes the test first.

```mermaid {alt="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." caption="The testing series: write the check, see what ran, see what was checked, replace collaborators, write the test first."}
flowchart TD
  A["JUnit 5"] --> B["JaCoCo"]
  B --> C["PIT"]
  C --> D["Mockito"]
  D --> E["TDD"]
  class A hl
  class B,C c1
  class D,E muted
```

## References

- [JUnit 5 user guide (5.14.4)](https://docs.junit.org/5.14.4/user-guide/): [annotations](https://docs.junit.org/5.14.4/writing-tests/annotations.html), [assertions](https://docs.junit.org/5.14.4/writing-tests/assertions.html), [test instance lifecycle](https://docs.junit.org/5.14.4/writing-tests/test-instance-lifecycle.html), [execution order](https://docs.junit.org/5.14.4/writing-tests/test-execution-order.html), [parameterized tests](https://docs.junit.org/5.14.4/writing-tests/parameterized-classes-and-tests.html), [nested tests](https://docs.junit.org/5.14.4/writing-tests/nested-tests.html), [build support](https://docs.junit.org/5.14.4/running-tests/build-support.html)
- [`java.time.Clock`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/Clock.html)
