How to read Maven properties from JUnit test?

吃可爱长大的小学妹 提交于 2019-12-05 01:21:39

Look at the systemPropertyVariables (and friends) for surefire. It does what you want. AFAIK there is no way to just pass all the maven properties without listing them.

Maven project properties aren't automatically added to Java System properties. To achieve that there are quite a few options. For this specific need you could define a System property for maven-surefire-plugin (the one running tests) and then use the System.getProperty method.

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

Other way to achieve getting Maven properties to JUnit tests would probably be resources filtering for test source files.

PS. Reading Maven configurations at runtime, even in tests is pretty dirty IMHO. :)

Sometimes, Eclipse is configured to use the Java Builder for Project->Automatically Build (Right Click->Project->Properties->Builders)

If such is the case, sometimes the resource filtering doesn't work. You have several options:

  1. Provide the property in the pom.xml file as above.
  2. Provide a properties file and perform Maven resource filtering
  3. Use the Maven Invoker

2 and 3 are described in http://scottizu.wordpress.com/2013/10/16/reading-the-project-version-from-the-maven-pom-file/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!