Priority in TestNG


In automation, many times we are required to configure our test suite to run test methods in a specific order or we have to give precedence to certain test methods over others. TestNG allows us to handle scenarios like these by providing a priority attribute within @Test annotation. By seeting the value of this priority attribute we can order the test methods as our need.

Priority parameter

We can assign a priority value to a test method like this-

@Test(priority=1)

The tests with lower priority value will get executed first. Example-

Default priority

The default priority of test when not specified is integer value 0. So, if we have one test case with priority 1 and one without any priority value then the test without any priority value will get executed first (as default value will be 0 and tests with lower priority are executed first).

Code Snippet

@Test(priority = 1) 
public void testMethodA() { 
   System.out.println("Executing - testMethodA");
} 

@Test 
public void testMethodB() { 
   System.out.println("Executing - testMethodB");
}

@Test(priority = 2) 
public void testMethodC() { 
   System.out.println("Executing - testMethodC");
}

Output

Executing - testMethodB
Executing - testMethodA
Executing - testMethodC

Here, we can see that testMethodB got executed first as it had default priority of 0. Since the other tests had priority value as 1 and 2 hence, the execution order was testMethodB then testMethodA and then testMethodC.

PS: If we want to give a test method, priority higher than the default priority then we can simply assign a negative value to the priority attribute of that test method.
@Test(priority = -1) 
public void testMethod() { 
   System.out.println("Priority higher than default");
}