Setting Priority of Test Cases in TestNG
TestNG allows you to control the order of test execution using the priority attribute in the @Test annotation.
Basic priority usage:
Java
@Test(priority = 1)
public void loginTest() {
System.out.println("Login test — runs first");
}
@Test(priority = 2)
public void searchTest() {
System.out.println("Search test — runs second");
}
@Test(priority = 3)
public void logoutTest() {
System.out.println("Logout test — runs third");
}
Default priority is 0: Tests without a priority are assigned value 0 and run before those with higher numbers.
Java
@Test // priority = 0 (default) → runs first
public void defaultTest() { }
@Test(priority = 1) // runs second
public void firstPriorityTest() { }
@Test(priority = -1) // negative priority → runs before 0
public void negativeTest() { }
Execution order rule: Lower value = executes first.
| priority value | Execution order |
|---|---|
| -1 | 1st |
| 0 (default) | 2nd |
| 1 | 3rd |
| 2 | 4th |
Same priority — alphabetical order: If two tests have the same priority, TestNG runs them in alphabetical order by method name.
Real-world example:
Java
public class E2ETest {
@Test(priority = 1)
public void openBrowser() { }
@Test(priority = 2)
public void login() { }
@Test(priority = 3)
public void addToCart() { }
@Test(priority = 4)
public void checkout() { }
@Test(priority = 5)
public void logout() { }
}
Key points:
- ✓
prioritycontrols execution order (lower = earlier) - ✓Default priority = 0 when not specified
- ✓Tests with lower priority run before tests with higher priority
- ✓Combine with
dependsOnMethodsfor more explicit control
