2011-10-26 40 views
6

我正在使用Maven 3.0.3和JUnit 4.8.1。在我的JUnit测试中,如何阅读在我的Maven pom.xml文件中定义的project.artifactId?在我的POM,我有如何从JUnit测试中读取Maven属性?

<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:空”。无论如何,感谢任何帮助, - 戴夫

+0

的可能的复制被描述[如何检索JUnit测试内行家属性?] (http://stackoverflow.com/questions/247346/how-to-retrieve-maven-properties-inside-a-junit-test) – approxiblue

回答

5

看看systemPropertyVariables(和朋友)为surefire。它做你想要的。 AFAIK没有办法只是通过所有的maven属性,没有列出它们。

9

Maven项目属性不会自动添加到Java系统属性中。为了达到这个目的,有很多选择。对于这个特定的需求,你可以为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> 

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

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

+1

使用systemPropertyVariables而不是systemProperties(不建议使用) –

相关问题