In TestNG, controlling the order of test execution is essential when you have multiple test classes that need to follow a specific sequence. TestNG, by default, execute the test alphabetically, but it offers the flexibility to customize by using the testng.xml file. Using the preserve-order attribute along with parallel="none" ensures classes and test methods execute in a particular order. This ensures predictability in the execution of tests, which can be important when tests are interdependent or form a natural sequence.
Approach to maintain the order of execution as mentioned in TestNG.xml
Following are the steps to maintain the order of execution as mentioned in TestNG.xml
- Create classes: First create two java classes (eg:TestClass1 and TestClass2) on any ide like Eclipse or IntelliJ
- Add Test Methods: Add Test Methods in each class using @test annotation and write your logic in that test method.
- Create testng.xml file: Create a TestNG.xml file in your project folder.
- Add Parameters in testing.xml file: Add parameters like parallel and preserve-order in the testing.xml file. At the suite level add parameter parallel="none" and at test, level add parameter preserve-order="true", this will maintain the order of execution as mentioned in TestNG.xml.
- Run the project: Run the TestNG project by right-clicking on the testng.xml file and selecting run as 1 TestNg Suite.
Example Code
TestClass1.java
package com.example;
import org.testng.annotations.Test;
public class TestClass1 {
@Test
public void testMethod1() {
System.out.println("TestClass1 - testMethod1");
}
}
TestClass2.java
package com.example;
import org.testng.annotations.Test;
public class TestClass2 {
@Test
public void testMethod2() {
System.out.println("TestClass2 - testMethod2");
}
}
testng.xml
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd" >
<suite name="Suite" parallel="none">
<test name="Test1" preserve-order="true">
<classes>
<!-- The classes will be executed in the order they are listed here -->
<class name="com.example.TestClass1"/>
<class name="com.example.TestClass2"/>
</classes>
</test>
</suite>
- The parallel="none" attribute ensures that no parallel execution is performed. This is crucial when tests need to be run sequentially.
- The preserve-order="true" attribute inside the <test> tag guarantees that the classes and their respective test methods are executed in the order they are listed in the XML configuration file.
Conclusion
The order of execution is ensured exactly the way you declare it by setting up parallel as none and preserve order as true in the testng.xml file. It's really helpful if the execution order is particularly important for the results of the tests.