在我的單元測試中,我想在$ {project.build.directory}中創建一個tmp目錄。我如何在單元測試中訪問$ {project.build.directory}的值?
我可以想到的一種方法是在測試資源中提供一個過濾的屬性文件,該文件具有該值。 (我還沒有嘗試,但我認爲這應該工作。)
是否有直接的方式來訪問/傳遞此屬性值?
問候, 弗洛裏安
在我的單元測試中,我想在$ {project.build.directory}中創建一個tmp目錄。我如何在單元測試中訪問$ {project.build.directory}的值?
我可以想到的一種方法是在測試資源中提供一個過濾的屬性文件,該文件具有該值。 (我還沒有嘗試,但我認爲這應該工作。)
是否有直接的方式來訪問/傳遞此屬性值?
問候, 弗洛裏安
記住,你的單元測試不必從Maven的萬無一失插件來執行,因此${project.build.directory}
屬性可能不可用。爲了使您的測試更便攜,我寧願推薦使用File.createTempFile()
。
我認爲使用系統屬性是非常簡單的,如果你配置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>
我已經使用過這樣的事情,並取得了一些成功。即使不使用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;
}
可能我們可以配置設置系統屬性,但不知何故我不喜歡這個想法通過系統屬性傳遞的東西。另一方面,你可以說這是特定環境(至少是絕對路徑)。你怎麼看? – Puce 2011-02-09 18:27:00