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.

Share

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, @Nested, extensions) plus the engine that runs those tests on the Platform.
  • 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.

JUnit versions
VersionReleasedJavaKey points
JUnit 420065+@Test, runners and rules; still widely used
JUnit 5.020178+Platform, Jupiter and Vintage; extensions replace runners and rules
JUnit 5.x (to 5.13)2017 to 20258+Many additions, such as @TempDir, @Timeout, @ParameterizedClass
JUnit 6.0September 202517+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.

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

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 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"));
    }
}
Jupiter features used above
FeaturePurpose
@TestA test method; test classes and methods need not be public
@BeforeEachRuns before every test
@DisplayNameA readable name in reports
@ParameterizedTest with @CsvSource or @ValueSourceOne method run once per row, with arguments converted to the parameter types (here BigDecimal and int)
@NestedGroups related tests in an inner class that shares the outer setup
assertThrowsAsserts that code throws, and returns the exception for further checks
assertAllRuns 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.

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

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
  • The parameterized test ran three times, once per CSV row, each named from its arguments. The nested tests and both @ValueSource quantities ran separately: 8 tests from 5 test methods.
  • The assertAll test reported both wrong checks. With separate assertEquals calls, the first failure would have stopped the test and hidden the second.
  • The scale check failed because BigDecimal.equals treats 3.3 and 3.30 as different, which is why the other tests write expected values with two decimals.
  • Test methods run in a deterministic but deliberately unspecified order. Tests must not depend on each other; use @TestMethodOrder only when order is part of what is tested.

In a project, the same tests run with mvn test or gradle test after adding org.junit.jupiter:junit-jupiter as a test dependency.

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 lifecycle and increments a field in two tests, so the difference in instances shows in the counter values.

Java
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):

Output
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
  • @BeforeAll ran once before everything and @AfterAll once at the very end. In the default lifecycle both must be static, because no instance exists yet.
  • counter was 1 in both first and second: each test got a new instance, so the increment from the first test was gone. This isolation is the default, PER_METHOD.
  • In the PER_CLASS nested class, shared went from 1 to 2, because one instance served both tests, and its @BeforeAll could be an instance method. Use this when setup is expensive, but reset any state yourself.
  • The outer class's @BeforeEach and @AfterEach also wrapped the nested tests: nested classes inherit the outer setup.

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.

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

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
  • @MethodSource("listsAndSizes") supplied a List argument, which a CSV string cannot express.
  • @EnumSource with names ran only SATURDAY and SUNDAY, not all seven days.
  • @NullAndEmptySource added null and "", and the CSV rows added three spaces and a tab: four runs from one method. Quoting with ' is how @CsvSource keeps leading and trailing whitespace.
  • @TestFactory returned three dynamic tests built at run time. Their names came from the data, which suits tests generated from files or tables.
  • The failure message says expected: <avaj> but was: <java>, which is backwards: the test passed the reversed word as the expected value. assertEquals(expected, actual) takes the expected value first, and swapping them gives misleading reports like this one.

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

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

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
  • @Disabled and @EnabledOnOs(OS.WINDOWS) skipped their tests before running them, with the reason in the report. Skipped tests count as neither passed nor failed.
  • assumeTrue aborted needsDatabase at run time because TEST_DB_URL was not set. An aborted test is reported separately from a failure, so a missing environment does not turn the build red.
  • @Timeout let tooSlow sleep its full 500 ms and then failed it with TimeoutException. assertTimeoutPreemptively 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 prefer @Timeout.
  • With the tag filter only the two "fast" tests were discovered. Build tools expose the same filter, for example mvn test -Dgroups=fast with Surefire.

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 ParameterResolver that injects a fixed Clock, so time-dependent code is testable, and before and after callbacks that time each test using the extension store.

Java
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));
    }
}
Java
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:

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
  • usesInjectedClock received the fixed clock and saw the date 2026-01-15 whatever the real date was. writesReport received a Path from the built-in @TempDir support, which creates a fresh directory per test and deletes it afterwards.
  • 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.
  • @ExtendWith registered the extension for the whole class. Libraries ship their own: MockitoExtension, Spring's SpringExtension and Testcontainers' @Testcontainers all work this way.

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

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

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, "10.00" x "1", where JUnit 5 printed 10.00 x 1. Tools or tests that match display names need updating.
  • 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 junit-platform-runner is removed; @CsvSource now uses FastCSV and rejects extra characters after a closing quote; and deprecated APIs such as MethodOrderer.Alphanumeric are gone.

Choosing the right tool

Which JUnit feature to use
NeedUse
The same check over many inputs@ParameterizedTest with @CsvSource, @MethodSource or @EnumSource
Tests generated from data at run time@TestFactory with dynamic tests
Several checks on one resultassertAll
Expensive shared setup@BeforeAll, or PER_CLASS lifecycle
Tests that need an environmentAssumptions, or @EnabledIf... conditions
Separate fast and slow suites@Tag and the build tool's tag filter
Reusable setup or injectionAn extension
New project in 2026JUnit 6 on Java 17 or later; JUnit 5 if you must support older Java

For mocks of collaborators see Mockito; for more readable assertions see AssertJ.