JUnit 5 (and 6): testing in Java
JUnit 5 is the standard testing framework for Java. This page explains how its Platform, engines and Jupiter API fit together, then runs real tests: assertions and parameterized tests, the lifecycle order, more parameter sources and dynamic tests, tags, assumptions and timeouts, a custom extension, and finally the same tests on JUnit 6. Every result shown is what the JUnit Platform reported.
Contents
How JUnit 5 is put together
JUnit 4 was a single JAR that both defined the test API and ran the tests, so build tools and IDEs had to reach into its internals. JUnit 5 split that into three parts:
- JUnit Platform: the foundation that discovers and runs tests. Its Launcher API is what Maven Surefire, Gradle and IDEs call. It knows nothing about annotations; it delegates to engines.
- JUnit Jupiter: the programming model you write tests with (
,@Test ,@ParameterizedTest , extensions) plus the engine that runs those tests on the Platform.@Nested - JUnit Vintage: an engine that runs old JUnit 3 and 4 tests on the Platform, for migration.
When the Launcher runs, it asks each engine on the class path to discover tests from selectors (a class, a package, a method), builds a tree of containers and tests, applies filters such as tags, and executes the tree while reporting events to listeners. A test class is a container, each test method is a test, and a parameterized method is a container whose invocations are the tests. For every test, Jupiter creates a fresh instance of the test class by default, so fields cannot leak state from one test to the next.
| Version | Released | Java | Key points |
|---|---|---|---|
| JUnit 4 | 2006 | 5+ | @Test |
| JUnit 5.0 | 2017 | 8+ | Platform, Jupiter and Vintage; extensions replace runners and rules |
| JUnit 5.x (to 5.13) | 2017 to 2025 | 8+ | Many additions, such as @TempDir@Timeout@ParameterizedClass |
| JUnit 6.0 | September 2025 | 17+ | One version number for all modules, JSpecify nullability, Vintage deprecated, FastCSV for @CsvSource |
The tests below were run with JUnit Jupiter 5.12.2 on JDK 21, and the last section reruns them with JUnit 6.0.3.
A first test class
A small price calculator gives something to test on both the happy and the error paths: price times quantity, minus a percentage discount, rounded to cents, rejecting a non-positive quantity and a discount outside 0 to 100.
import java.math.BigDecimal;
import java.math.RoundingMode;
// The class under test
public class PriceCalculator {
public BigDecimal total(BigDecimal unitPrice, int quantity, int discountPercent) {
if (quantity <= 0) {
throw new IllegalArgumentException("quantity must be positive: " + quantity);
}
if (discountPercent < 0 || discountPercent > 100) {
throw new IllegalArgumentException("discount out of range: " + discountPercent);
}
BigDecimal gross = unitPrice.multiply(BigDecimal.valueOf(quantity));
BigDecimal factor = BigDecimal.valueOf(100 - discountPercent).movePointLeft(2);
return gross.multiply(factor).setScale(2, RoundingMode.HALF_UP);
}
}
The test class uses the most common Jupiter features in one place. The last test is deliberately wrong in two places, to show what a failure report looks like. The middle CSV row was chosen because 39.98 × 0.75 = 29.985 lands exactly on a rounding boundary, so it checks the rounding mode, not just the arithmetic.
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 java.math.BigDecimal;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
@DisplayName("PriceCalculator")
class PriceCalculatorTest {
PriceCalculator calc;
@BeforeEach
void setUp() {
calc = new PriceCalculator(); // a fresh instance for every test
}
@Test
@DisplayName("multiplies price by quantity")
void noDiscount() {
assertEquals(new BigDecimal("7.50"), calc.total(new BigDecimal("2.50"), 3, 0));
}
@ParameterizedTest(name = "{0} x {1} with {2}% off = {3}")
@CsvSource({
"10.00, 1, 10, 9.00",
"19.99, 2, 25, 29.99", // 39.98 * 0.75 = 29.985, rounded half up
"5.00, 4, 100, 0.00"
})
void discounts(BigDecimal price, int qty, int discount, BigDecimal expected) {
assertEquals(expected, calc.total(price, qty, discount));
}
@Nested
@DisplayName("rejects invalid input")
class InvalidInput {
@ParameterizedTest(name = "quantity {0}")
@ValueSource(ints = {0, -1})
void quantity(int qty) {
IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
() -> calc.total(BigDecimal.ONE, qty, 0));
assertEquals("quantity must be positive: " + qty, e.getMessage());
}
@Test
@DisplayName("discount above 100")
void discount() {
assertThrows(IllegalArgumentException.class, () -> calc.total(BigDecimal.ONE, 1, 101));
}
}
@Test
@DisplayName("assertAll reports every failed check, not just the first")
void severalChecks() {
BigDecimal result = calc.total(new BigDecimal("1.10"), 3, 0);
assertAll(
() -> assertEquals(new BigDecimal("3.30"), result),
() -> assertEquals(2, result.scale()),
() -> assertEquals(new BigDecimal("3.3"), result, "deliberately wrong: scale"),
() -> assertEquals(-1, result.signum(), "deliberately wrong: sign"));
}
}
| Feature | Purpose |
|---|---|
@Test | A test method; test classes and methods need not be public |
@BeforeEach | Runs before every test |
@DisplayName | A readable name in reports |
@ParameterizedTest@CsvSource@ValueSource | One method run once per row, with arguments converted to the parameter types (here BigDecimalint |
@Nested | Groups related tests in an inner class that shares the outer setup |
assertThrows | Asserts that code throws, and returns the exception for further checks |
assertAll | Runs all checks and reports every failure together |
Running tests with the Launcher
To show results on this page, a small program does what a build tool does: it builds a discovery request, optionally adds a tag filter, runs it, and prints each result and a summary. Every other output on this page comes from this runner.
import static org.junit.platform.engine.discovery.DiscoverySelectors.selectClass;
import java.util.ArrayList;
import java.util.List;
import org.junit.platform.engine.TestExecutionResult;
import org.junit.platform.launcher.Launcher;
import org.junit.platform.launcher.TagFilter;
import org.junit.platform.launcher.TestExecutionListener;
import org.junit.platform.launcher.TestIdentifier;
import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder;
import org.junit.platform.launcher.core.LauncherFactory;
import org.junit.platform.launcher.listeners.SummaryGeneratingListener;
// Runs test classes with the JUnit Platform, as Maven, Gradle and IDEs do, and prints results.
// Arguments: test class names, and optionally "tag:name" to run only tests with that tag
public class RunTests {
public static void main(String[] args) throws Exception {
LauncherDiscoveryRequestBuilder builder = LauncherDiscoveryRequestBuilder.request();
List<String> tags = new ArrayList<>();
for (String arg : args.length > 0 ? args : new String[] {"PriceCalculatorTest"}) {
if (arg.startsWith("tag:")) {
tags.add(arg.substring(4));
} else {
builder.selectors(selectClass(Class.forName(arg)));
}
}
if (!tags.isEmpty()) {
builder.filters(TagFilter.includeTags(tags));
}
TestExecutionListener printer = new TestExecutionListener() {
@Override
public void executionSkipped(TestIdentifier id, String reason) {
System.out.println("SKIP " + id.getDisplayName() + " (" + reason + ")");
}
@Override
public void executionFinished(TestIdentifier id, TestExecutionResult result) {
if (id.isTest()) {
String status = switch (result.getStatus()) {
case SUCCESSFUL -> "PASS";
case ABORTED -> "ABORT";
case FAILED -> "FAIL";
};
System.out.println(status + " " + id.getDisplayName());
result.getThrowable().ifPresent(t -> System.out.println(" "
+ t.getClass().getSimpleName() + ": " + t.getMessage()));
}
}
};
SummaryGeneratingListener summary = new SummaryGeneratingListener();
Launcher launcher = LauncherFactory.create();
launcher.execute(builder.build(), printer, summary);
var s = summary.getSummary();
System.out.println("tests: " + s.getTestsFoundCount() + ", passed: "
+ s.getTestsSucceededCount() + ", failed: " + s.getTestsFailedCount()
+ ", aborted: " + s.getTestsAbortedCount() + ", skipped: "
+ s.getTestsSkippedCount());
}
}
Output for PriceCalculatorTest
PASS 10.00 x 1 with 10% off = 9.00
PASS 19.99 x 2 with 25% off = 29.99
PASS 5.00 x 4 with 100% off = 0.00
PASS multiplies price by quantity
FAIL assertAll reports every failed check, not just the first
MultipleFailuresError: Multiple Failures (2 failures)
org.opentest4j.AssertionFailedError: deliberately wrong: scale ==> expected: <3.3> but was: <3.30>
org.opentest4j.AssertionFailedError: deliberately wrong: sign ==> expected: <-1> but was: <1>
PASS quantity 0
PASS quantity -1
PASS discount above 100
tests: 8, passed: 7, failed: 1, aborted: 0, skipped: 0
- The parameterized test ran three times, once per CSV row, each named from its arguments. The nested tests and both
quantities ran separately: 8 tests from 5 test methods.@ValueSource - The
test reported both wrong checks. With separateassertAll calls, the first failure would have stopped the test and hidden the second.assertEquals - The scale check failed because
treats 3.3 and 3.30 as different, which is why the other tests write expected values with two decimals.BigDecimal.equals - Test methods run in a deterministic but deliberately unspecified order. Tests must not depend on each other; use
only when order is part of what is tested.@TestMethodOrder
In a project, the same tests run with mvn testgradle testorg.junit.jupiter:junit-jupiter
The lifecycle, step by step
The order of setup and teardown calls, and how many test instances exist, decide what state tests share. The test class logs every callback into a static list. The nested class switches to PER_CLASS
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
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.TestInstance;
import org.junit.jupiter.api.TestMethodOrder;
// Records the order of lifecycle callbacks and which test instance runs each test
@TestMethodOrder(MethodOrderer.MethodName.class)
class LifecycleTest {
static final List<String> LOG = new ArrayList<>();
int counter = 0; // a fresh copy for every test
@BeforeAll
static void beforeAll() {
LOG.add("@BeforeAll");
}
@BeforeEach
void beforeEach() {
LOG.add(" @BeforeEach");
}
@Test
void first() {
counter++;
LOG.add(" first, counter = " + counter);
}
@Test
void second() {
counter++;
LOG.add(" second, counter = " + counter);
}
@AfterEach
void afterEach() {
LOG.add(" @AfterEach");
}
@AfterAll
static void afterAll() {
LOG.add("@AfterAll");
}
// PER_CLASS: one instance for all tests, so fields are shared and @BeforeAll can be
// an instance method
@Nested
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@TestMethodOrder(MethodOrderer.MethodName.class)
class SharedInstance {
int shared = 0;
@BeforeAll
void setUpOnce() {
LOG.add("PER_CLASS @BeforeAll (instance method)");
}
@Test
void a() {
shared++;
LOG.add(" PER_CLASS a, shared = " + shared);
}
@Test
void b() {
shared++;
LOG.add(" PER_CLASS b, shared = " + shared);
}
}
}
Output (results, then the logged call order):
PASS first()
PASS second()
PASS a()
PASS b()
tests: 4, passed: 4, failed: 0, aborted: 0, skipped: 0
call order:
@BeforeAll
@BeforeEach
first, counter = 1
@AfterEach
@BeforeEach
second, counter = 1
@AfterEach
PER_CLASS @BeforeAll (instance method)
@BeforeEach
PER_CLASS a, shared = 1
@AfterEach
@BeforeEach
PER_CLASS b, shared = 2
@AfterEach
@AfterAll
ran once before everything and@BeforeAll once at the very end. In the default lifecycle both must be@AfterAll , because no instance exists yet.static was 1 in bothcounter andfirst : each test got a new instance, so the increment from the first test was gone. This isolation is the default,second .PER_METHOD- In the
nested class,PER_CLASS went from 1 to 2, because one instance served both tests, and itsshared could be an instance method. Use this when setup is expensive, but reset any state yourself.@BeforeAll - The outer class's
and@BeforeEach also wrapped the nested tests: nested classes inherit the outer setup.@AfterEach
More argument sources and dynamic tests
Besides CSV rows, Jupiter has several other argument sources. The class below uses a factory method, an enum filter, null and empty values, generated dynamic tests and a repeated test. One palindrome is deliberately wrong.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.time.DayOfWeek;
import java.util.List;
import java.util.stream.Stream;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.RepetitionInfo;
import org.junit.jupiter.api.TestFactory;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.EnumSource;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.NullAndEmptySource;
class SourcesTest {
// @MethodSource: arguments built in code, including objects CSV cannot express
static Stream<Arguments> listsAndSizes() {
return Stream.of(Arguments.of(List.of(), 0), Arguments.of(List.of("a", "b"), 2));
}
@ParameterizedTest(name = "size of {0} is {1}")
@MethodSource("listsAndSizes")
void sizes(List<String> list, int expected) {
assertEquals(expected, list.size());
}
// @EnumSource with a filter: only the weekend constants
@ParameterizedTest(name = "{0} is a weekend day")
@EnumSource(value = DayOfWeek.class, names = {"SATURDAY", "SUNDAY"})
void weekend(DayOfWeek day) {
assertTrue(day.getValue() >= 6);
}
// null and "" from @NullAndEmptySource, plus blank strings from @CsvSource
@ParameterizedTest(name = "[{0}] is blank")
@NullAndEmptySource
@CsvSource({"' '", "'\t'"})
void blank(String s) {
assertTrue(s == null || s.isBlank());
}
// Dynamic tests: generated at run time, one per data item
@TestFactory
Stream<DynamicTest> palindromes() {
return Stream.of("level", "noon", "java").map(word -> DynamicTest.dynamicTest(
word + " is a palindrome",
() -> assertEquals(new StringBuilder(word).reverse().toString(), word)));
}
@RepeatedTest(value = 3, name = "repetition {currentRepetition} of {totalRepetitions}")
void repeated(RepetitionInfo info) {
assertTrue(info.getCurrentRepetition() <= 3);
}
}
Output:
PASS repetition 1 of 3
PASS repetition 2 of 3
PASS repetition 3 of 3
PASS [null] is blank
PASS [] is blank
PASS [ ] is blank
PASS [ ] is blank
PASS size of [] is 0
PASS size of [a, b] is 2
PASS level is a palindrome
PASS noon is a palindrome
FAIL java is a palindrome
AssertionFailedError: expected: <avaj> but was: <java>
PASS SATURDAY is a weekend day
PASS SUNDAY is a weekend day
tests: 14, passed: 13, failed: 1, aborted: 0, skipped: 0
supplied a@MethodSource("listsAndSizes") argument, which a CSV string cannot express.List with@EnumSource ran only SATURDAY and SUNDAY, not all seven days.names added@NullAndEmptySource andnull , and the CSV rows added three spaces and a tab: four runs from one method. Quoting with"" is how' keeps leading and trailing whitespace.@CsvSource returned three dynamic tests built at run time. Their names came from the data, which suits tests generated from files or tables.@TestFactory- The failure message says
, which is backwards: the test passed the reversed word as the expected value.expected: <avaj> but was: <java> takes the expected value first, and swapping them gives misleading reports like this one.assertEquals(expected, actual)
Tags, disabled tests, assumptions and timeouts
Real suites need to control which tests run where: slow tests only on CI, platform-specific tests only on that platform, integration tests only when a database is configured. The class covers each mechanism, and the runner executes it twice: once completely and once with only the tag "fast".
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
// Controlling which tests run: tags, disabling, conditions, assumptions and timeouts
class ControlTest {
@Test
@Tag("fast")
void fastCheck() {
assertEquals(4, 2 + 2);
}
@Test
@Tag("slow")
void slowCheck() throws InterruptedException {
Thread.sleep(50);
}
@Test
@Disabled("waiting for bug 123 to be fixed")
void brokenFeature() {
}
@Test
@EnabledOnOs(OS.WINDOWS)
void windowsOnly() {
}
@Test
@Tag("fast")
void needsDatabase() {
assumeTrue(System.getenv("TEST_DB_URL") != null, "TEST_DB_URL not set");
}
@Test
@Timeout(value = 100, unit = TimeUnit.MILLISECONDS)
void tooSlow() throws InterruptedException {
Thread.sleep(500);
}
@Test
void preemptive() {
assertTimeoutPreemptively(Duration.ofMillis(100), () -> Thread.sleep(500));
}
}
Output:
--- all tests
FAIL preemptive()
AssertionFailedError: execution timed out after 100 ms
SKIP brokenFeature() (waiting for bug 123 to be fixed)
ABORT needsDatabase()
TestAbortedException: Assumption failed: TEST_DB_URL not set
FAIL tooSlow()
TimeoutException: tooSlow() timed out after 100 milliseconds
PASS fastCheck()
PASS slowCheck()
SKIP windowsOnly() (Disabled on operating system: Linux)
tests: 7, passed: 2, failed: 2, aborted: 1, skipped: 2
--- only tag "fast"
ABORT needsDatabase()
TestAbortedException: Assumption failed: TEST_DB_URL not set
PASS fastCheck()
tests: 2, passed: 1, failed: 0, aborted: 1, skipped: 0
and@Disabled skipped their tests before running them, with the reason in the report. Skipped tests count as neither passed nor failed.@EnabledOnOs(OS.WINDOWS) abortedassumeTrue at run time becauseneedsDatabase was not set. An aborted test is reported separately from a failure, so a missing environment does not turn the build red.TEST_DB_URL let@Timeout sleep its full 500 ms and then failed it withtooSlow .TimeoutException ran the code in another thread and abandoned it after 100 ms. Preemptive timeouts break code that depends on the current thread, such as thread-bound transactions, so preferassertTimeoutPreemptively .@Timeout- With the tag filter only the two "fast" tests were discovered. Build tools expose the same filter, for example
with Surefire.mvn test -Dgroups=fast
Extensions
JUnit 4 had runners and rules; JUnit 5 replaces both with extensions, small classes that implement callback interfaces. This one implements two kinds: a ParameterResolverClock
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.extension.AfterTestExecutionCallback;
import org.junit.jupiter.api.extension.BeforeTestExecutionCallback;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.ParameterContext;
import org.junit.jupiter.api.extension.ParameterResolver;
// An extension that times each test and injects a fixed Clock into test parameters
public class FixedClockExtension implements ParameterResolver, BeforeTestExecutionCallback,
AfterTestExecutionCallback {
static final List<String> TIMINGS = new ArrayList<>();
private static final ExtensionContext.Namespace NS =
ExtensionContext.Namespace.create(FixedClockExtension.class);
@Override
public boolean supportsParameter(ParameterContext p, ExtensionContext e) {
return p.getParameter().getType() == Clock.class;
}
@Override
public Object resolveParameter(ParameterContext p, ExtensionContext e) {
return Clock.fixed(Instant.parse("2026-01-15T10:00:00Z"), ZoneOffset.UTC);
}
@Override
public void beforeTestExecution(ExtensionContext context) {
context.getStore(NS).put("start", System.nanoTime());
}
@Override
public void afterTestExecution(ExtensionContext context) {
long start = context.getStore(NS).get("start", Long.class);
long ms = (System.nanoTime() - start) / 1000000;
TIMINGS.add(context.getDisplayName() + " took under 1 s: " + (ms < 1000));
}
}
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Clock;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.io.TempDir;
@ExtendWith(FixedClockExtension.class)
class ExtensionTest {
@Test
void usesInjectedClock(Clock clock) {
assertEquals("2026-01-15", clock.instant().toString().substring(0, 10));
}
// @TempDir: a fresh directory per test, deleted afterwards
@Test
void writesReport(@TempDir Path dir) throws Exception {
Path report = dir.resolve("report.txt");
Files.writeString(report, "3 orders");
assertTrue(Files.exists(report));
assertEquals("3 orders", Files.readString(report));
}
}
Output:
PASS writesReport(Path)
PASS usesInjectedClock(Clock)
tests: 2, passed: 2, failed: 0, aborted: 0, skipped: 0
extension: writesReport(Path) took under 1 s: true
extension: usesInjectedClock(Clock) took under 1 s: true
received the fixed clock and saw the date 2026-01-15 whatever the real date was.usesInjectedClock received awritesReport from the built-inPath support, which creates a fresh directory per test and deletes it afterwards.@TempDir- The timing callbacks ran around both tests. The store keeps per-test state inside JUnit, which is safer than fields on the extension when tests run in parallel.
registered the extension for the whole class. Libraries ship their own:@ExtendWith , Spring'sMockitoExtension and Testcontainers'SpringExtension all work this way.@Testcontainers
The same tests on JUnit 6
JUnit 6 keeps the Jupiter API, so tests normally move without changes. To check, the program starts a second JVM whose class path holds the classes compiled above and the JUnit 6.0.3 jars instead of 5.12.2, and runs PriceCalculatorTest
import java.io.File;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.stream.Collectors;
// Runs the same compiled tests in a second JVM whose class path has JUnit 6 instead of 5.
// -Djunit6.cp must point to the JUnit 6 jars
public class RunOnJunit6 {
public static void main(String[] args) throws Exception {
String classes = Arrays.stream(System.getProperty("java.class.path")
.split(File.pathSeparator)).filter(e -> !e.endsWith(".jar"))
.collect(Collectors.joining(File.pathSeparator)); // only our own classes
String cp = classes + File.pathSeparator + System.getProperty("junit6.cp");
ProcessBuilder pb = new ProcessBuilder(Path.of(System.getProperty("java.home"), "bin",
"java").toString(), "-cp", cp, "RunTests", "PriceCalculatorTest");
pb.environment().remove("JAVA_TOOL_OPTIONS");
Process p = pb.redirectErrorStream(true).start();
System.out.print(new String(p.getInputStream().readAllBytes()));
p.waitFor();
System.out.println("JUnit Platform version in that JVM: " + version(cp));
}
static String version(String cp) {
return Arrays.stream(cp.split(File.pathSeparator))
.filter(e -> e.contains("junit-platform-launcher"))
.map(e -> e.replaceAll(".*junit-platform-launcher-", "").replace(".jar", ""))
.findFirst().orElse("?");
}
}
Output:
PASS "10.00" x "1" with "10"% off = "9.00"
PASS "19.99" x "2" with "25"% off = "29.99"
PASS "5.00" x "4" with "100"% off = "0.00"
PASS multiplies price by quantity
FAIL assertAll reports every failed check, not just the first
MultipleFailuresError: Multiple Failures (2 failures)
org.opentest4j.AssertionFailedError: deliberately wrong: scale ==> expected: <3.3> but was: <3.30>
org.opentest4j.AssertionFailedError: deliberately wrong: sign ==> expected: <-1> but was: <1>
PASS quantity 0
PASS quantity -1
PASS discount above 100
tests: 8, passed: 7, failed: 1, aborted: 0, skipped: 0
JUnit Platform version in that JVM: 6.0.3
- The same 8 tests ran with the same single failure, without recompiling. Classes compiled against JUnit 5.12 ran unchanged on JUnit 6.
- One visible difference: the display names of the parameterized test now show the string arguments in quotes,
, where JUnit 5 printed"10.00" x "1" . Tools or tests that match display names need updating.10.00 x 1 - Other JUnit 6 changes, from its release notes: Java 17 is the minimum; Platform, Jupiter and Vintage share one version number (Platform was 1.x before); the Vintage engine is deprecated and
is removed;junit-platform-runner now uses FastCSV and rejects extra characters after a closing quote; and deprecated APIs such as@CsvSource are gone.MethodOrderer.Alphanumeric
Choosing the right tool
| Need | Use |
|---|---|
| The same check over many inputs | @ParameterizedTest@CsvSource@MethodSource@EnumSource |
| Tests generated from data at run time | @TestFactory |
| Several checks on one result | assertAll |
| Expensive shared setup | @BeforeAllPER_CLASS |
| Tests that need an environment | Assumptions, or @EnabledIf... |
| Separate fast and slow suites | @Tag |
| Reusable setup or injection | An extension |
| New project in 2026 | JUnit 6 on Java 17 or later; JUnit 5 if you must support older Java |
For mocks of collaborators see