Testing / JUnit6 Interview Questions
What is the CancellationToken API introduced in JUnit 6?
One of the headline new features in JUnit 6 is the CancellationToken API -- a cooperative cancellation mechanism that allows launchers (Gradle, Maven, IntelliJ, GitHub Actions) to signal a running test suite to stop cleanly, without killing the JVM process.
The problem it solves: in JUnit 5, there was no clean way to abort a long-running test suite mid-run. Build tools had to forcibly kill the JVM, which skipped teardown methods, left database connections open, and could leave the CI environment in an inconsistent state.
// JUnit 6: CancellationToken -- test and extension authors can check // for cancellation between steps and abort cleanly. // Extensions can check cancellation: class CleanupExtension implements BeforeEachCallback { @Override public void beforeEach(ExtensionContext context) throws Exception { // Check if the test run has been cancelled before starting setup if (context.getCancellationToken().isCancellationRequested()) { return; // skip setup gracefully } // ... normal setup ... } } // --fail-fast mode in ConsoleLauncher: // The first test failure triggers a CancellationToken that propagates // through the test suite, stopping remaining tests cleanly. java -jar junit-platform-console-standalone-6.1.1.jar \ --scan-class-path \ --fail-fast // Equivalent in Maven Surefire: // <configuration> // <runOrder>random</runOrder> // <forkCount>1</forkCount> // </configuration> // (use --fail-at-end or failIfNoTests per tool docs)
| Scenario | JUnit 5 | JUnit 6 with CancellationToken |
|---|---|---|
| CI cancels long-running build | JVM killed; teardown skipped; resources leaked | Cooperative signal; @AfterEach and @AfterAll run; connections closed |
| --fail-fast mode | Not available | First failure signals cancellation; remaining tests skipped cleanly |
| Parallel test suite cancelled | Threads killed; database in inconsistent state | Each thread checks token between steps; graceful exit |
More Related questions...