JUnit 5测试中的临时目录
JUnit 4 TemporaryFolder @Rule允許開發人員使用臨時目錄創建測試。 使用JUnit 5時,不支持@Rule因此測試文件和目錄需要一些額外的工作。 幸運的是,有了JUnit 5.4,有一個新的內置擴展可以處理測試中的臨時目錄。 而且它非常易于使用。
您還在使用JUnit 4嗎? 請參閱我以前的有關使用TemporaryFolder @Rule在JUnit 4中測試文件和目錄的文章。
@TempDir
可以使用@org.junit.jupiter.api.io.TempDir注釋來注釋類字段或生命周期中的參數(例如@BeforeEach )或File或Path類型的測試方法。 完成此操作后,將創建臨時目錄。 一旦測試方法或類執行完畢,將刪除在測試執行過程中創建的目錄及其內容。
要測試的代碼
在這個簡單的示例中,我們將測試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您可以輕松地在測試中使用臨時目錄。 這里沒有魔術:您可以注釋Path或File對象并根據需要進行注入。 其余的工作由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
總結
以上是生活随笔為你收集整理的JUnit 5测试中的临时目录的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 松下洗衣机电脑板主板价格(panason
- 下一篇: 世界笔记本电脑排名(全世界笔记本电脑排名