How to read Maven properties from JUnit test?

I am using Maven 3.0.3 with JUnit 4.8.1. In my JUnit test, how can I read project.artifactId defined in my Maven pom.xml file? In my pom, I

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

But this does not work in my JUnit test to get the artifact id ...

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

The above outputs are "artifactId: null". Anyway, appreciate any help, - Dave

+10
source share
3 answers

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

+7
source

Maven project properties are not automatically added to Java system properties. There are many options for this. For this specific need, you can define the System property for the maven-surefire-plugin (those that run the 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> 

Another way to achieve Maven properties for JUnit tests is probably by filtering resources for the source source files.

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

+10
source

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

If so, sometimes resource filtering does not work. You have several options:

  • Provide the property in the pom.xml file as described above.
  • Provide a properties file and filter Maven resources
  • Use Maven Invoker

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

0
source

Source: https://habr.com/ru/post/900137/


All Articles