How to define environment variables in java-maven project?

779 views Asked by At

I am developing a hybrid framework that is used for testing UI and API.

I want to execute the same tests in QA and UAT environments. I have .properties file for qa and uat. And a testng.xml file that will execute the tests. I have UI and API tests that are environment specific.

I want to define a universal environment variable that when passed during maven execution (mvn test) will be read by the .properties file reader before executing the UI or API tests - How / where can i define this environment variable ?

2

There are 2 answers

0
Adarsh On
            <configuration>
                <environmentVariables>
                    <environemnt>${environemnt}</environemnt>
                    <browser>${browser}</browser>
                </environmentVariables>
            </configuration>

When the above configurations is added under maven-surefire-plugin in pom.xml file, required testng.xml file can be executed in required environment and browser. e.g.,

mvn test -Denvironment=qa -Dbrowser=firefox -DsuiteXmlFile=testng_ui.xml

2
Prashant On

Usually when you are creating a framework (assuming from scratch; not recommended as there are many you could directly choose from and then customise to suite your needs) you should be responsible for reading the properties file. Now removing this detail from the equation, you can put your "universal environment variable" directly in your pom file. Here is a solution:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>${maven-surefire-plugin.version}</version>
    <configuration>
        <systemProperties>
            <property>
                <name>myUniversalProperty</name>
                <value>Same in all envs</value>
            </property>
        </systemProperties>
    </configuration>
</plugin>

Now this will allow you to read the value using System.getProperty("myUniversalProperty") expression. Note that the <value> in this case can also be passed as command line argument while running the application.