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 |
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
