2013-07-25 44 views
1

我有一些將文件寫入我選擇的目錄的代碼。我目前有一個測試,它使用JUnit Theories來運行這個代碼與許多不同的目錄。它看起來類似於:創建用於靜態方法的靜態方法中的Junit測試的臨時目錄

@DataPoints 
public static File[] produceListOfDirs() { 
    return new File[] { 
     new File("some directory path here") 
    } 
} 

@Theory 
public void myTest(File f) { 
    ... run my code being tested with f ... 
} 

的問題是,我想有獲得創建的目錄(以及獲得在其中創建的文件)測試完成移除(無論是成功或失敗)。

理想的應該只是使用@Rule來指定一個臨時目錄&使用它:

@Rule 
public TemporaryFolder testFolder = new TemporaryFolder(); 

@DataPoints 
public static File[] produceListOfDirs() { 
    return new File[] { 
     new File(testFolder.getRoot()) 
    } 
} 

@Theory 
public void myTest(File f) { 
    ... run my code being tested with f ... 
} 

但是,當然,這裏的問題是,@DataPoints只能註釋靜態方法和TemporaryFolder規則必須不是靜止的。

任何優雅的解決方案呢?

回答

2

嘗試在方法上使用@BeforeClass批註將所需的目錄或文件設置爲測試類的字段。然後可以使用@AfterClass註釋將其撕下。

private static File directory; 
@BeforeClass 
public static void setup() { 
     directory = new File("/path/to/file"); 
     if(!directory.exists()){ 
      directory.mkdir(); 
     } 
} 

@AfterClass 
public static void teardown() { 
     if(directory.exists()){ 
      FileUtils.deleteDirectory(directory); //apache-commons-io 
     } 
} 

@BeforeClass

有時幾個測試需要共享計算昂貴的安裝 (如登錄到數據庫)。雖然這可能會影響測試的獨立性,但有時候這是一種必要的優化。 使用@BeforeClass註釋公共靜態void no-arg方法會導致 它會在類中的任何測試方法之前運行一次。超類的@BeforeClass方法將在當前類的 之前運行。 Documentation

@AfterClass

如果您在BeforeClass方法分配昂貴的外部資源 你需要釋放他們在類中的所有測試都運行之後。 使用@AfterClass註釋公共靜態void方法會導致 方法在類中的所有測試運行之後運行。所有 @AfterClass方法保證運行,即使BeforeClass方法 引發異常。在超類 中聲明的@AfterClass方法將在當前類的那些之後運行。 Documentation

+0

@AdamParkin這會適合您的情況嗎? –

+0

完美,像魅力一樣工作。儘管'@ After'方法中有一個錯字,如果它存在(如果exists()檢查前面的'!'否定不應該存在),那麼該目錄應該被刪除。唯一不同的是我通過'UUID'隨機創建目錄名稱,將它放入系統範圍的臨時目錄並在try/catch中包含'deleteDirectory()'調用。要點:https://gist.github.com/pzelnip/6080964 –

+0

@AdamParkin真棒的東西!我希望能夠從您那裏聽到這個消息。很好的問題! –