Note
|
JUnit Jupiter 5.4 introduced a built-in We’ve tackled this problem again, and introduced a resource-based extension in version 1.9.0. It allows temporary directories to be created that last longer than a single test method. Give it a try! |
The TempDirectory
extension can be used to create and clean up a temporary directory for an individual test or all tests in a test class.
To use it, simply register the extension and add a parameter of type java.nio.file.Path
to your test or lifecycle method or constructor.
For example, the following test registers the extension for a single test method, creates and writes a file to the temporary directory and checks its content.
@Test
@ExtendWith(TempDirectory.class)
void test(@TempDir Path tempDir) {
Path file = tempDir.resolve("test.txt");
writeFile(file);
assertExpectedFileContent(file);
}
In addition to the default file system, the extension can be used with any FileSystem
implementation, e.g. Jimfs.
In order to use a custom file system, simply register the extension programmatically and pass a provider of a custom parent directory of type Path
.
The following example uses the Jimfs FileSystem
and passes a custom tmp
parent directory to the static factory method TempDirectory::createInCustomDirectory
.
class MyTests {
private static FileSystem fileSystem;
@BeforeAll
static void createFileSystem() {
fileSystem = Jimfs.newFileSystem();
}
@AfterAll
static void closeFileSystem() throws Exception {
fileSystem.close();
}
@RegisterExtension
Extension tempDirectory = TempDirectory.createInCustomDirectory(() ->
Files.createDirectories(fileSystem.getPath("tmp")));
@Test
void test(@TempDir Path tempDir) {
Path file = tempDir.resolve("test.txt");
writeFile(file);
assertExpectedFileContent(file);
}
}
Thread-Safety
This extension’s thread-safety is undetermined, we recommend to be cautious when using it during parallel test execution. (We’re working on it.)