开发者

JUnit + Maven: accessing ${project.build.directory} value

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?

One way, which I could think of, is to provid开发者_运维技巧e 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?


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.

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


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:

<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>


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().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜