junit5_JUnit 5测试中的临时目录

junit5

junit5

JUnit 4 TemporaryFolder @Rule允许开发人员使用临时目录创建测试。 使用JUnit 5时,不支持@Rule因此测试文件和目录需要一点点额外的工作。 幸运的是,有了JUnit 5.4,有一个新的内置扩展可以处理测试中的临时目录。 而且它非常易于使用。

您还在使用JUnit 4吗? 请参阅我以前的有关使用TemporaryFolder @Rule在JUnit 4中测试文件和目录的文章。

@TempDir

可以使用@org.junit.jupiter.api.io.TempDir注释来注释类字段或生命周期中的参数(例如@BeforeEach )或FilePath类型的测试方法。 完成此操作后,将创建临时目录。 一旦测试方法或类执行完毕,将删除在测试执行过程中创建的目录及其内容。

要测试的代码

在这个简单的示例中,我们将测试FileWriter类,该类具有将文本内容写入新文件的单个方法:

 public class FileWriter { 
    public void writeTo(String path, String content) throws IOException {

        Path target = Paths.get(path);

        if (Files.exists(target)) {

            throw new IOException( "file already exists" );

        }

        Files.copy( new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8)), target);

    }
 }

@TemDir作为测试方法参数

在此示例中,我们将使用@TempDir注释对测试参数进行注释:

 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))

    );
 }

@TempDir作为实例字段

 import org.junit.jupiter.api.io.TempDir;
 class FileWriterTest { 
    private FileWriter fileWriter = new FileWriter(); 
    @TempDir

    Path tempDir;

    @BeforeEach

    void beforeEach() {

        assertTrue(Files.isDirectory( this .tempDir));

    }

    @RepeatedTest ( 3 )

    void throwsErrorWhenTargetFileExists() throws IOException {

        // arrange

        Path output = Files.createFile(

                tempDir.resolve( "output.txt" )

        );

        // act & assert

        IOException expectedException = assertThrows(IOException. class , () -> fileWriter.writeTo(output.toString(), "test" ));

        assertEquals( "file already exists" , expectedException.getMessage());

    }
 }

根据上面的示例,我们可以看到测试的每次重复都使用一个新的临时目录(根据标准测试类生命周期),因此该方法的ranging部分执行无误。

共享的临时目录

如果需要在测试方法之间共享一个临时目录,我们可以创建一个静态字段并重用该临时目录,如下例所示:

 import org.junit.jupiter.api.io.TempDir;
 class FileWriterTest { 
    private FileWriter fileWriter = new FileWriter(); 
    @TempDir

    static Path tempDir; 
    @BeforeAll

    static void setUp() {

        assertTrue(Files.isDirectory(tempDir));

    }

    @RepeatedTest ( 3 )

    void throwsErrorWhenTargetFileExists(RepetitionInfo repetitionInfo) throws IOException {

        // arrange

        Path output = Files.createFile(

                tempDir.resolve(repetitionInfo.getCurrentRepetition() + "_output.txt" )

        );

        // act & assert

        IOException expectedException = assertThrows(IOException. class , () -> fileWriter.writeTo(output.toString(), "test" ));

        assertEquals( "file already exists" , expectedException.getMessage());

    }
 }

请注意,测试方法的FileAlreadyExistsException会在每次执行时(使用当前的重复计数器)创建唯一的文件名,否则会抛出FileAlreadyExistsException

概要

使用@TempDir您可以轻松地在测试中使用临时目录。 这里没有魔术:您可以注释PathFile对象并根据需要进行注入。 其余的工作由JUnit替您完成。

在我的GitHub存储库中找到示例: https//github.com/kolorobot/junit5-samples/tree/master/junit5-built-in-extensions

翻译自: https://www.javacodegeeks.com/2019/03/temporary-directories-junit-5-tests.html

junit5

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值