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 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.
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.
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.
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.
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);
}
}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.
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.
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)
);
}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.
| 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.
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);
}
}
}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.
assertAll is fine
when the checks describe the same behaviour.)largeOrderShipsFree tells you more than test1, and reads well
in a failure report. Say what happens, and under which condition.for (double total = 100; total < 105; total++) {
double expected = total >= 100 ? 0 : 7.99;
assertEquals(expected, calc.cost(new Order(total, false)), 0.001);
}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);but was: <22.990000000000002>). Pass a delta.assertEquals(22.99, calc.cost(new Order(50, true)));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));static fields are
not.)private static final List<Order> orders = new ArrayList<>();Clock into the code, and use a fixed clock (Clock.fixed(...)) in the test.LocalDate today = LocalDate.now();LocalDate today = LocalDate.now(clock);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.
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);
}
}“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.
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.