Search code examples
javajunittemporary-filesjunit5

What is the equivalent of ExternalResource and TemporaryFolder in JUnit 5?


According to the JUnit 5 User Guide, JUnit Jupiter provides backwards compatibility for some JUnit 4 Rules in order to assist with migration.

As stated above, JUnit Jupiter does not and will not support JUnit 4 rules natively. The JUnit team realizes, however, that many organizations, especially large ones, are likely to have large JUnit 4 codebases including custom rules. To serve these organizations and enable a gradual migration path the JUnit team has decided to support a selection of JUnit 4 rules verbatim within JUnit Jupiter.

The guide goes on to say that one of the rules is ExternalResource, which is a parent for TemporaryFolder.

However, the guide unfortunately doesn't go on to say what the migration path is, or what the equivalent is for those writing new JUnit 5 tests. So what should we use?


Solution

  • JUnit 5.4 comes with a built-in extension to handle temporary directories in tests.

    @org.junit.jupiter.api.io.TempDir annotation can be used in order to annotate class field or a parameter in a lifecycle (e.g. @BeforeEach) or test method of type File or Path.

    import org.junit.jupiter.api.io.TempDir;
    
    @Test
    void writesContentToFile(@TempDir Path tempDir) throws IOException {
        // arrange
        Path output = tempDir
                .resolve("output.txt");
    
        // act
        fileWriter.writeTo(output.toString(), "test");
    
        // assert
        assertAll(
                () -> assertTrue(Files.exists(output)),
                () -> assertLinesMatch(List.of("test"), Files.readAllLines(output))
        );
    }
    

    You can read more on this in my blog post, where you will find some more examples on utilizing this built-in extension: https://blog.codeleak.pl/2019/03/temporary-directories-in-junit-5-tests.html.