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

后端 未结 5 2428
心在旅途
心在旅途 2021-02-19 02:20

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 ab

5条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-19 03:04

    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.

提交回复
热议问题