您的位置:軟件測(cè)試 > 開源軟件測(cè)試 > 開源單元測(cè)試工具 > junit
在JUnit中使用@Rule測(cè)試文件和目錄
作者:網(wǎng)絡(luò)轉(zhuǎn)載 發(fā)布時(shí)間:[ 2015/5/13 10:40:25 ] 推薦標(biāo)簽:單元測(cè)試工具

  伴隨JUnit中 TemporaryFolder @Rule 的出現(xiàn),測(cè)試文件和目錄變得簡(jiǎn)單了。
  在 JUnit 中,規(guī)則(@Rule)可作為構(gòu)造測(cè)試用具(fixture)時(shí)初始化方法和清理方法的替代和補(bǔ)充(在 JUnit 中,這2種方法分別通過以下注解標(biāo)注:org.junit.Before、org.junit.After、org.junit.BeforeClass 和 org.junit.AfterClass) 。而且規(guī)則的功能更加強(qiáng)大并且也更易于在項(xiàng)目和類之間共享。
  譯者注:測(cè)試用具是指作為測(cè)試運(yùn)行基準(zhǔn)的一組對(duì)象所呈現(xiàn)的一個(gè)穩(wěn)定狀態(tài)。其目的是確保測(cè)試是運(yùn)行在一個(gè)眾所周知的、穩(wěn)定的環(huán)境中的,以實(shí)現(xiàn)測(cè)試的可重復(fù)執(zhí)行。準(zhǔn)備輸入數(shù)據(jù)、生成模擬對(duì)象(Mock)、將特定的數(shù)據(jù)加載到數(shù)據(jù)庫(kù)、復(fù)制一組特定的文件等,這些都屬于構(gòu)造測(cè)試用具。
  待測(cè)試的代碼
  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("UTF8")), target);
  }
  測(cè)試類
public class FileWriterTest {
private FileWriter fileWriter = new FileWriter();
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void throwsErrorWhenTargetFileExists() throws IOException {
// arrange
File output = temporaryFolder.newFile("output.txt");
thrown.expect(IOException.class);
thrown.expectMessage("file already exists");
// act
fileWriter.writeTo(output.getPath(), "test");
}
@Test
public void writesContentToFile() throws IOException {
// arrange
File output = temporaryFolder.newFolder("reports")
.toPath()
.resolve("output.txt")
.toFile();
// act
fileWriter.writeTo(output.getPath(), "test");
// assert
assertThat(output)
.hasContent("test")
.hasExtension("txt")
.hasParent(resolvePath("reports"));
}
private String resolvePath(String folder) {
return temporaryFolder
.getRoot().toPath()
.resolve(folder)
.toString();
}
}
  譯者注:第35行的 assertThat() 是類 org.assertj.core.api.Assertions 中的靜態(tài)方法。
  TemporaryFolder 提供了2個(gè)方法 newFile 和 newFolder,分別用于管理文件和目錄。這2個(gè)方法都可以返回所需要的對(duì)象。返回的文件或目錄都是由 setup 方法創(chuàng)建的并被存放在臨時(shí)目錄中。要想獲取臨時(shí)目錄自身的路徑,可以使用 TemporaryFolder 的 getRoot 方法。
  無(wú)論測(cè)試成功與否,任何在測(cè)試過程中添加到臨時(shí)目錄的文件或目錄都會(huì)在測(cè)試結(jié)束時(shí)刪除。
  本示例可以從我在 GitHub 上的項(xiàng)目 unit-testing-demo 中找到,除此之外該項(xiàng)目中還有很多其他示例可供諸位參考。

軟件測(cè)試工具 | 聯(lián)系我們 | 投訴建議 | 誠(chéng)聘英才 | 申請(qǐng)使用列表 | 網(wǎng)站地圖
滬ICP備07036474 2003-2017 版權(quán)所有 上海澤眾軟件科技有限公司 Shanghai ZeZhong Software Co.,Ltd