2011-02-09 16 views
24

在我的單元測試中,我想在$ {project.build.directory}中創建一個tmp目錄。我如何在單元測試中訪問$ {project.build.directory}的值?

我可以想到的一種方法是在測試資源中提供一個過濾的屬性文件,該文件具有該值。 (我還沒有嘗試,但我認爲這應該工作。)

是否有直接的方式來訪問/傳遞此屬性值?

問候, 弗洛裏安

+0

可能我們可以配置設置系統屬性,但不知何故我不喜歡這個想法通過系統屬性傳遞的東西。另一方面,你可以說這是特定環境(至少是絕對路徑)。你怎麼看? – Puce 2011-02-09 18:27:00

回答

5

記住,你的單元測試不必從Maven的萬無一失插件來執行,因此${project.build.directory}屬性可能不可用。爲了使您的測試更便攜,我寧願推薦使用File.createTempFile()

+2

實際上,這就是我們目前所做的,我想改變這一點。我們遇到了一個問題,哈德森上的tmp目錄被填滿,直到磁盤空間用完。我們正在研究幾個選項,一個是在目標目錄內傳遞一個tmp目錄作爲File.createTempFile()的參數。像這樣,「mvn clean」會清理所有內容。 – Puce 2011-02-09 18:21:39

+0

此外,因爲這是一個Maven項目,我認爲測試只能使用Maven或支持Maven的IDE(這裏是:Eclipse)來運行。 – Puce 2011-02-09 18:24:18

12

我認爲使用系統屬性是非常簡單的,如果你配置surefire插件,這裏解釋http://maven.apache.org/plugins/maven-surefire-plugin/examples/system-properties.html。即使這個例子直接回答你的問題:

<project> 
    [...] 
    <build> 
    <plugins> 
     <plugin> 
     <groupId>org.apache.maven.plugins</groupId> 
     <artifactId>maven-surefire-plugin</artifactId> 
     <version>2.9</version> 
     <configuration> 
      <systemPropertyVariables> 
      <propertyName>propertyValue</propertyName> 
      <buildDirectory>${project.build.directory}</buildDirectory> 
      [...] 
      </systemPropertyVariables> 
     </configuration> 
     </plugin> 
    </plugins> 
    </build> 
    [...] 
</project> 
14

我已經使用過這樣的事情,並取得了一些成功。即使不使用Maven,單元測試仍然會運行,相對於運行測試的任何地方的cwd,目標目錄仍然會創建兩個dir。

public File targetDir(){ 
    String relPath = getClass().getProtectionDomain().getCodeSource().getLocation().getFile(); 
    File targetDir = new File(relPath+"../../target"); 
    if(!targetDir.exists()) { 
    targetDir.mkdir(); 
    } 
    return targetDir; 
} 
相關問題