JUnit + Maven:访问$ {project.build.directory}值

Puc*_*uce 25 java junit maven

在我的单元测试中,我想在$ {project.build.directory}中创建一个tmp目录.如何在单元测试中访问$ {project.build.directory}的值?

我能想到的一种方法是在测试资源中提供过滤的属性文件,该文件保留该值.(我还没有尝试,但我认为这应该有效.)

是否有直接访问/传递此属性值的方法?

此致,弗洛里安

Upg*_*ave 18

我曾经使用过这样的东西并取得了一些成功.即使不使用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;
}
Run Code Online (Sandbox Code Playgroud)


Adr*_*nRM 14

我认为如果你按照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>
Run Code Online (Sandbox Code Playgroud)


Tom*_*icz 5

请记住,您的单元测试不必从Maven surefire插件执行,因此${project.build.directory}可能无法使用属性.为了使您的测试更便携,我宁愿推荐使用File.createTempFile().

  • 嗯,实际上,这就是我们目前的工作,我想改变它.我们遇到了一个问题,即Hudson上的tmp目录已经填满,直到我们的磁盘空间不足为止.我们正在研究几个选项,一个是将目标目录中的tmp目录作为参数传递给File.createTempFile().像这样,"mvn clean"会清理一切. (3认同)