10

我将 Maven 3.0.3 与 JUnit 4.8.1 一起使用。在我的 JUnit 测试中,如何读取我的 Maven pom.xml 文件中定义的 project.artifactId?在我的 pom 中,我有

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.myco.pplus2</groupId>
<artifactId>pplus2</artifactId>

但这在我的 JUnit 测试中无法获取工件 id ...

@Before
public void setUp() { 
    ...        
    System.out.println( "artifactId:" + System.getProperty("project.build.sourceEncoding") ); 
}   // setUp

以上输出“artifactId:null”。无论如何,感谢任何帮助, - 戴夫

4

3 回答 3

10

Maven 项目属性不会自动添加到 Java 系统属性中。要实现这一点,有很多选择。对于这一特定需求,您可以为 maven-surefire-plugin (正在运行的测试)定义一个系统属性,然后使用 System.getProperty 方法。

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.10</version>
    <configuration>
        <systemProperties>
            <property>
                <name>projectArtifactId</name>
                <value>${project.artifactId}</value>
            </property>
        </systemProperties>
    </configuration>
</plugin>

实现将 Maven 属性获取到 JUnit 测试的其他方法可能是对测试源文件进行资源过滤。

PS。恕我直言,在运行时读取 Maven 配置,即使在测试中也是如此。:)

于 2011-10-26T20:30:53.207 回答
7

看看systemPropertyVariables(和朋友)是肯定的。它做你想做的事。AFAIK 没有办法只通过所有 Maven 属性而不列出它们。

于 2011-10-26T19:53:05.203 回答
0

有时,Eclipse 被配置为使用 Java Builder for Project->Automatically Build(右键单击->Project->Properties->Builders)

如果是这种情况,有时资源过滤不起作用。你有几个选择:

  1. 如上所述在 pom.xml 文件中提供属性。
  2. 提供属性文件并执行 Maven 资源过滤
  3. 使用 Maven 调用程序

2和3在http://scottizu.wordpress.com/2013/10/16/reading-the-project-version-from-the-maven-pom-file/中有描述

于 2013-10-16T18:46:08.133 回答