Ram
Ram

Reputation: 445

Getting variables from pom.xml java

I am using eclipse with maven for a mobile automation test on a mobile webpage.

I am defining the following in my pom.xml

<properties>
    <MY_VARIABLE>www.google.com/</MY_VARIABLE>
</properties>

but when i am calling this using

String testurl1 = System.getProperty("MY_VARIABLE");

it always seems to return null.

I also tried the following way of defining variable

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.16</version>
    <configuration>
        <systemPropertyVariables>
        <MY_VARIABLE>www.google.com</MY_VARIABLE>
        </systemPropertyVariables>
    </configuration>
</plugin>

but still am getting the value as null.

I could use some help Thanks.

Upvotes: 5

Views: 9964

Answers (1)

Ren&#233; Link
Ren&#233; Link

Reputation: 51353

Your configuration will not work in eclipse since there is no good m2e support for surefire. The maven surefire plugin forkes a new process and provides the systemPropertyVariables to it. Your configuration will work if you run the tests from the command-line, e.g.

mvn surefire:test

To make it run in both worlds (command-line and eclipse) I do it this way...

  1. Create a src/test/resources/maven.properties
  2. Edit the maven.properties file and put the properties you need in it, e.g.

    project.build.directory=${project.build.directory}
    MY_VARIABLE=${MY_VARIABLE}
    
  3. Enable resource filtering for test resources

    <build>
        <testResources>
            <testResource>
                <directory>src/test/resources</directory>
                <filtering>true</filtering>
            </testResource>
        </testResources>
        ...
    </build>
    
  4. Load the properties in your test and access them

     Properties mavenProps = new Properties();
     InputStream in = TestClass.class.getResourceAsStream("/maven.properties");
     mavenProps.load(in);
    
     String buildDir = mavenProps.getProperty("project.build.directory");
     String myVar = mavenProps.getProperty("MY_VARIABLE");
    

Upvotes: 6

Related Questions