【问题标题】:JUnit + Maven: accessing ${project.build.directory} valueJUnit + Maven:访问 ${project.build.directory} 值
【发布时间】:2011-06-24 07:45:39
【问题描述】:

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

我能想到的一种方法是在测试资源中提供一个过滤的属性文件,该文件包含该值。 (我还没有尝试过,但我认为应该可以。)

有没有直接访问/传递这个属性值的方法?

【问题讨论】:

  • 也许我们可以配置为设置系统属性,但不知何故我不喜欢通过系统属性传递东西的想法。另一方面,您可以说这是特定于环境的东西(至少是绝对路径)。你怎么看?

标签: java maven junit


【解决方案1】:

我以前使用过类似的东西并取得了一些成功。即使不使用 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;
}

【讨论】:

  • 讨论稍晚,但relPath 不等于src/main/java,所以您肯定需要解决以../../../target 为目标吗?
【解决方案2】:

如果您按照此处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>

【讨论】:

    【解决方案3】:

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

    【讨论】:

    • 嗯,实际上,这就是我们目前所做的,我想改变它。我们遇到了一个问题,即 Hudson 上的 tmp 目录被填满,直到我们用完磁盘空间。我们正在研究几个选项,一个是将目标目录中的 tmp 目录作为参数传递给 File.createTempFile()。像这样,“mvn clean”会清理一切。
    • 此外,由于这是一个 Maven 项目,我认为测试只能使用 maven 或支持 Maven 的 IDE(此处为 Eclipse)运行。
    • 我有另一个反对意见 - 我们在 Mac 和 Windows 上使用 TestContainers 时遇到问题 - 临时文件无法绑定到 docker 容器内。
    猜你喜欢
    • 2023-03-24
    • 2016-03-22
    • 1970-01-01
    • 1970-01-01
    • 2011-03-03
    • 2013-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多