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.
Example Java Code for Priority in TestNG
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)"); } }
Output:
Test A - Priority 0 Test D - Default Priority (0) Test C - Priority 1 Test B - Priority 2
Important points:
testA()
and testD()
both have priority 0
. Since testA()
comes alphabetically before testD()
, 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
priority
value = executed earlierSame
priority
value = no guaranteed order among those methodsExample Code: Same Priority Test Methods
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"); } }
Output:
Test D - Priority 0 Test A - Priority 1 Test B - Priority 1 Test C - Priority 1
Another Run Might Give:
Test D - Priority 0 Test C - Priority 1 Test A - Priority 1 Test B - Priority 1
If multiple test methods share the same priority, TestNG may run them in any order. So, do not rely on order of execution if you assign the same priority to multiple test methods.
No comments:
Post a Comment