java JUnit + Maven:访问 ${project.build.directory} 值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4948457/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JUnit + Maven: accessing ${project.build.directory} value
提问by Puce
In my unit tests I want to create a tmp directory inside the ${project.build.directory}. How can I access the value of ${project.build.directory} inside my unit test?
在我的单元测试中,我想在 ${project.build.directory} 中创建一个 tmp 目录。如何在单元测试中访问 ${project.build.directory} 的值?
One way, which I could think of, is to provide a filtered properties file in the test resources, which holdes that value. (I haven't tried yet, but I think that should work.)
我能想到的一种方法是在测试资源中提供一个过滤的属性文件,其中包含该值。(我还没有尝试过,但我认为应该可以。)
Is there a direct way to access/ pass this property value?
有没有直接的方法来访问/传递这个属性值?
回答by Upgradingdave
I've used something like this with some success before. The unit test will still run even if not using Maven, the target directory will still get created two dirs up relative to the cwd of wherever the tests are run.
我以前使用过类似的东西并取得了一些成功。即使不使用 Maven,单元测试仍将运行,目标目录仍将相对于运行测试的 cwd 创建两个目录。
public File targetDir(){
String relPath = getClass().getProtectionDomain().getCodeSource().getLocation().getFile();
File targetDir = new File(relPath+"../../target");
if(!targetDir.exists()) {
targetDir.mkdir();
}
return targetDir;
}
回答by AdrianRM
I think using system properties is quite straightforward if you configure the surefire-plugin as explained here http://maven.apache.org/plugins/maven-surefire-plugin/examples/system-properties.html. Even the example there is answering your question directly:
我认为,如果您按照http://maven.apache.org/plugins/maven-surefire-plugin/examples/system-properties.html 中的说明配置surefire-plugin,则使用系统属性非常简单。甚至那里的例子也直接回答了你的问题:
<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>
回答by Tomasz Nurkiewicz
Remember, that your unit tests don't have to be executed from Maven surefire plugin, so ${project.build.directory}
property might not be available. To make your tests more portable I would rather recommend using File.createTempFile()
.
请记住,您的单元测试不必从 Maven surefire 插件执行,因此${project.build.directory}
属性可能不可用。为了使您的测试更便携,我宁愿建议使用File.createTempFile()
.