Testing / JUnit6 Interview Questions
What is the @TempDir annotation and how has it changed in JUnit 6?
@TempDir creates a temporary directory for a test and automatically deletes it after the test completes. JUnit 6 adds a cleanup attribute to control when (and whether) the directory is deleted, enabling inspection of files after a failing test.
import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.api.io.CleanupMode; class TempDirDemo { // Field injection: directory shared across all tests in class @TempDir static Path sharedTempDir; // Parameter injection: fresh directory per test method @Test void writeAndReadFile(@TempDir Path tempDir) throws Exception { Path file = tempDir.resolve("output.txt"); Files.writeString(file, "Hello JUnit 6"); assertEquals("Hello JUnit 6", Files.readString(file)); // tempDir is automatically deleted after this test } // JUnit 6: cleanup attribute -- control when directory is deleted @Test void keepDirOnFailure( @TempDir(cleanup = CleanupMode.ON_SUCCESS) Path debugDir ) throws Exception { Files.writeString(debugDir.resolve("log.txt"), "debug info"); // If test PASSES: directory is deleted // If test FAILS: directory is KEPT for inspection } // cleanup modes: // ALWAYS (default): always delete // ON_SUCCESS: keep on failure (useful for debugging) // NEVER: never delete (manual cleanup) }
| Mode | When deleted |
|---|---|
| CleanupMode.ALWAYS | Always deleted after test (default) |
| CleanupMode.ON_SUCCESS | Only deleted if test passes; kept on failure for debugging |
| CleanupMode.NEVER | Never automatically deleted |
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...
