如何从JUnit测试中读取Maven属性?

Dav*_*ave 10 junit system-properties maven

我正在使用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>
Run Code Online (Sandbox Code Playgroud)

但是这在我的JUnit测试中不起作用来设置工件ID ...

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

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

Ant*_*nen 10

Maven项目属性不会自动添加到Java System属性中.要实现这一目标,有很多选择.对于这个特定需求,您可以为maven-surefire-plugin(运行测试的那个)定义一个System属性,然后使用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>
Run Code Online (Sandbox Code Playgroud)

实现获取JUnit测试的Maven属性的其他方法可能是测试源文件的资源过滤.

PS.在运行时读取Maven配置,即使在测试中也很脏恕我直言.:)

  • 使用systemPropertyVariables而不是systemProperties(不建议使用) (5认同)

pty*_*tyx 7

查看systemPropertyVariables(和朋友)以获得万无一失.它做你想要的.AFAIK没有办法只传递所有maven属性而不列出它们.