What is priority in TestNG?
The TestNG Priority is a mechanism used to force a specific execution order among test methods that belong to the same TestNG class. By default, TestNG does not guarantee any particular order for running test methods within a class; they might run in alphabetical order or another unpredictable sequence. Priority allows the developer to override this default behavior.
In TestNG, the priority attribute is used to define the order of execution of test methods in a class.
Key Points about priority:
The lower the priority number, the earlier the method will run.
priority = 0will run beforepriority = 1, and so on.If no priority is specified, TestNG assigns it a default priority of 0.
You can assign negative values as well.
If two or more tests have the same priority, they run in alphabetical order.
import org.testng.annotations.Test; public class PriorityExample { @Test(priority = 1) public void testC() { System.out.println("Test C - Priority 1"); } @Test(priority = 0) public void testA() { System.out.println("Test A - Priority 0"); } @Test(priority = 2) public void testB() { System.out.println("Test B - Priority 2"); } @Test // No priority mentioned, default is 0 public void testD() { System.out.println("Test D - Default Priority (0)"); } }
Test A - Priority 0 Test D - Default Priority (0) Test C - Priority 1 Test B - Priority 2
testA()andtestD()both have priority0. SincetestA()comes alphabetically beforetestD(), it runs first.
- Priorities help in defining explicit flow of tests, especially in dependent or staged testing scenarios.
- In TestNG, when multiple test methods have the same priority, TestNG does not guarantee any specific execution order among them. It means that the methods with the same priority may be executed in any order, and this order can change across different runs.
- Lower
priorityvalue = executed earlier
- Same
priorityvalue = no guaranteed order among those methods
Below is the output shown the execution flow of all test methods. Please have a look.
import org.testng.annotations.Test; public class SamePriorityExample { @Test(priority = 1) public void testA() { System.out.println("Test A - Priority 1"); } @Test(priority = 1) public void testB() { System.out.println("Test B - Priority 1"); } @Test(priority = 1) public void testC() { System.out.println("Test C - Priority 1"); } @Test(priority = 0) public void testD() { System.out.println("Test D - Priority 0"); } }
Test D - Priority 0 Test A - Priority 1 Test B - Priority 1 Test C - Priority 1
Test D - Priority 0 Test C - Priority 1 Test A - Priority 1 Test B - Priority 1
Suggested Posts:
1. Introduction to TestNG
2. Annotations in TestNG
3. TestNG Asserts
4. First Script in TestNG
5. Parameterization in TestNG