What is priority
in TestNG?
In TestNG, the priority
attribute is used to define the order of execution of test methods in a class.
By default, TestNG executes test methods in alphabetical order of method names (not the order they appear in the code). If you want to control the execution order explicitly, you can assign a priority to each @Test
method.
Key Points about priority
:
The lower the priority number, the earlier the method will run.
priority = 0
will 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()
and testD()
both have priority 0
. Since testA()
comes alphabetically before testD()
, it runs first.priority
value = executed earlierpriority
value = no guaranteed order among those methodsimport 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