寫單測有時需要讀取磁盤上的檔案以測試讀、寫函數的功能是否正常,但是檔案路徑如果設定不恰當,路徑不存在 或者 程式對該路徑沒有通路權限,單測就會挂掉。有時候本地單測功能正常,一跑 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%