写单测有时需要读取磁盘上的文件以测试读、写函数的功能是否正常,但是文件路径如果设置不恰当,路径不存在 或者 程序对该路径没有访问权限,单测就会挂掉。有时候本地单测功能正常,一跑 CI 就挂了,很烦~~
这种场景下,临时文件就很好的解决了这个问题。
单测 demo:
package com.example.demo;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.nio.file.Files;
import java.nio.file.Path;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
@SpringBootTest
class DemoApplicationTests {
@Test
public void should_create_temp_file_write_and_read_succeed() {
String context = "create-temp-file-write-and-read";
try{
Path path = Files.createTempFile("temp-file",".txt");
System.out.println("temp-file-path: " + path.toString());
Files.write(path,context.getBytes());
String fetch = Files.readAllLines(path).get(0);
System.out.println("fetched context: " + fetch);
assertThat(fetch, is(context));
}catch (Exception e){
e.printStackTrace();
}
}
}
测试案例的代码逻辑很简单,测试结果如下:
temp-file-path: /var/folders/5s/w0fmzrbj17nd7d7kyz3vx0x40000gn/T/temp-file7412232211465511032.txt
fetched context: create-temp-file-write-and-read
查看创建的临时文件:
cat /var/folders/5s/w0fmzrbj17nd7d7kyz3vx0x40000gn/T/temp-file7412232211465511032.txt
create-temp-file-write-and-read%