Running Tests in Multiple Environments with Maven and System Properties in TestNG
In this blog, we’ll show how to run tests in different environments like QA, Prod, and Dev using Maven with System Properties in TestNG, without modifying your testng.xml or without passing any parameters tag to testng.xml / without using @paramters annotations.
Step 1: Configure testng.xml
Your testng.xml file should be simple and not include any parameters for environments.
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="RegressionTestSuite">
<test name="RegressionTest">
<classes>
<class name="com.example.tests.RegressionTest"/>
</classes>
</test>
</suite>
Step 2: Pass Environment Variables via Maven
Use Maven’s -D flag to pass environment-specific properties when running tests:
mvn test -Dtest.env=QA -Dtest.url=http://qa.example.com -DsuiteXmlFile=testng.xml
Step 3: Access Properties in Your Test Code
In your test code, access the properties using System.getProperty():
import org.testng.annotations.BeforeClass;
public class RegressionTest {
@BeforeClass
public void setUp() {
String environment = System.getProperty("test.env", "defaultEnv");
String url = System.getProperty("test.url", "http://default-url.com");
System.out.println("Running tests in Environment: " + environment);
System.out.println("Using URL: " + url);
}
}
Step 4: Run Tests for Different Environments
To run tests in different environments, simply change the -Dtest.env and -Dtest.url values in the Maven command:
Conclusion
Using Maven’s -D flag, you can pass different environment properties without changing your testng.xml. This makes it easy to run tests in various environments like QA, Prod, and Dev dynamically.
Happy Testing !
Software Engineer
8moHi can u suggest me what course u prefer to learn for above testing