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 |
More Related questions...