javajunit5

How to create a temp file in JUnit 5


I wrote a unit test with JUnit 5 that tests some file system logic for which I need a folder and some files. I found the TempDir annotation in the documentation and used that to create a folder, into which I saved some files. Something like:

@TempDir
static Path tempDir;

static Path tempFile;

// ...

@BeforeAll
public static void init() throws IOException {
    tempFile = Path.of(tempDir.toFile().getAbsolutePath(), "test.txt");
    if (!tempFile.toFile().createNewFile()) {
        throw new IllegalStateException("Could not create file " + tempFile.toFile().getAbsolutePath());
    }
    // ...
}

In JUnit 4 it was possible to use TemporaryFolder#newFile(String). This doesn't seem to be around in junit5.

Am I missing something? It works so I suppose that's fine but I was wondering if there is a cleaner way to create a new file directly with the JUnit 5 API.


Solution

  • You can simplify the amount of typing for getting temp files if you make use of the built in methods of Files. This is a more concise definition to provide tempFile which should give similar error handling:

    @TempDir
    static Path tempDir;
    static Path tempFile;
    
    @BeforeAll
    public static void init() throws IOException {
        tempFile = Files.createFile(tempDir.resolve("test.txt"));
    }
    

    Ensure that you have a recent version of JUnit 5. The test below should pass, but fails in some older versions of JUnit which do not generate unique values of @TempDir for fields tempDir and mydir:

    @Test void helloworld(@TempDir Path mydir) {
        System.out.println("helloworld() tempDir="+tempDir+" mydir="+mydir);
        assertFalse(Objects.equals(tempDir, mydir));
    }