junit 5中的tmpdir注解

在junit 5中,如何设置针对文件的测试呢?可以使用@TempDir这个注解,比如要测试一个文件的操作,如下:
 

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

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

测试用例:
 

import org.junit.jupiter.api.io.TempDir;
 
@Test
void writesContentToFile(@TempDir Path tempDir) throws IOException {
   
    Path output = tempDir
            .resolve("output.txt");
 
    //执行
    fileWriter.writeTo(output.toString(), "test");
 

    assertAll(
            () -> assertTrue(Files.exists(output)),
            () -> assertLinesMatch(List.of("test"), Files.readAllLines(output))
    );
}

注意这里都是用到不少NIO的知识了。
   也可以把tmpdir注解注解字段类型,比如:
   

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());
    }
}

 这里是在tempdir变量中加了注解,然后重复三次建立文件,并进行断言判断。
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值