In TestNG, we can set the execution order of test methods using the priority attribute. priority is a parameter for the @Test annotation that accepts an integer value. By default, TestNG executes test methods in ascending order of the priority value, with methods having lower priority values executed first.
For example, consider three test methods where we can control the execution order by setting different priority values:
javaimport org.testng.annotations.Test; public class PriorityExample { @Test(priority = 0) public void firstTest() { System.out.println("First test"); } @Test(priority = 1) public void secondTest() { System.out.println("Second test"); } @Test(priority = 2) public void thirdTest() { System.out.println("Third test"); } }
In this example, the firstTest method executes first because its priority value is 0, followed by secondTest with a priority value of 1, and finally thirdTest with a priority value of 2.
If the priority attribute is not set, TestNG executes test methods in dictionary order based on method names. Using the priority attribute helps ensure that the execution order meets our requirements, especially when some tests have dependencies.