JUnit Jupiter test structure
What you will learn
A unit test makes an observable contract executable: arrange an input, act on the unit, and assert the result. JUnit Jupiter supplies test annotations and assertions; the Platform discovers and launches test engines.
- Write a focused Jupiter test with a meaningful assertion.
- Distinguish test lifecycle, engine discovery and Java assertions.
- Check a successful purchase and a rejected input.
Prerequisite: Java exceptions, interfaces, Maven and Gradle. External framework examples are source-reviewed, NOT RUN; dependency-free examples are tested separately.
Receipt domain from V25
package example.books;
public final class Receipt { private Receipt() {} public static int totalCents(int count, int unitCents) { if (count < 0 || unitCents < 0) { throw new IllegalArgumentException("negative purchase"); } return Math.multiplyExact(count, unitCents); }}Complete existing production class. The contract is nonnegative count and price, exact multiplication or ArithmeticException on overflow.
Test layers and discovery
A unit test isolates a small behavior, such as computing receipt cents; an integration test exercises a boundary such as real database access. JUnit Platform launches engines, while Jupiter defines the programming and extension model. JUnit 6 requires Java 17 or newer at runtime; this chapter targets JDK 21, using fixed JUnit 6.0.2 rather than claiming the latest release. Maven and Gradle integration require compatible test engines and approved dependencies. The included Maven POM is a source-reviewed example only.
Arrange, act, assert
Give the test a name describing the rule. Arrange the smallest useful input, call the public contract, then compare actual behavior with an independent expectation. assertEquals(expected, actual) reports a mismatch. assertThrows accepts subclasses of the expected exception; assertThrowsExactly requires the exact type. Never catch AssertionError in a test meant to detect a wrong result. Java assert statements can be disabled by the runtime; JUnit assertion methods do not depend on -ea.
Fresh fixtures and lifecycle
Jupiter normally creates a fresh test instance for each test method. Use @BeforeEach and @AfterEach for independent setup and cleanup; @BeforeAll and @AfterAll normally use static methods unless PER_CLASS lifecycle applies. Avoid shared mutable state and dependence on test order. A successful build without discovered tests is not proof; inspect the runner report. A dependency-free Main harness checks the same rules without claiming Jupiter execution.
First Jupiter tests
package example.books;
import org.junit.jupiter.api.Test;import org.junit.jupiter.api.BeforeEach;import static org.junit.jupiter.api.Assertions.*;
class ReceiptTest { private int price;
@BeforeEach void setUp() { price = 250; }
@Test void multipliesCountByPrice() { assertEquals(750, Receipt.totalCents(3, price)); }
@Test void rejectsNegativeCount() { assertThrows(IllegalArgumentException.class, () -> Receipt.totalCents(-1, price)); }}Source-reviewed NOT RUN. Predicted two successful tests: 750 cents and negative count rejection. Place under src/test/java/example/books.
Dependency-free check
public class Main { static int total(int count, int price) { if (count < 0 || price < 0) throw new IllegalArgumentException(); return Math.multiplyExact(count, price); } public static void main(String[] args) { if (total(3, 250) != 750) throw new AssertionError("normal purchase"); if (total(0, 250) != 0) throw new AssertionError("empty purchase"); try { total(-1, 250); throw new AssertionError("negative accepted"); } catch (IllegalArgumentException expected) { } System.out.println("3 checks passed"); }}Locally executable example; expected stdout: 3 checks passed. This is not a JUnit runner.
Pin a test dependency
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>example.books</groupId> <artifactId>receipt-tests</artifactId> <version>1.0.0</version> <properties> maven.compiler.release>21 /maven.compiler.release> project.build.sourceEncoding>UTF-8 /project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter</artifactId> <version>6.0.2</version> <scope>test</scope> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>5.21.0</version> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.14.1</version> <configuration> <proc>none</proc> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>3.5.4</version> </plugin> </plugins> </build></project>Complete staged test project POM; NOT RUN. Maven, Jupiter, Mockito and coverage instrumentation are not installed. Use only a reviewed offline dependency cache.
Common mistakes
A test with no meaningful assertion can pass for incorrect code. Do not compare a method call with the same method call, depend on test order, or confuse -ea with Jupiter assertions.
Practice
Write a test plan for Receipt: normal purchase, zero count, and negative price. Provide independent expected values and an exception type. Explain how test discovery and setup are verified.
Use the manual practice hints; explain your reasoning before consulting the private review solution.
Official reading: overview · annotations · assertions · lifecycle.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JUnit Jupiter test structure — knowledge check
Testing and debugging knowledge check.
What is the role of Jupiter?
Which assertion uses an independent expected value?
What does assertThrows allow?
What is the usual test instance lifecycle?
What should be checked after a successful build?