</>

Technology

TestNG

Difficulty

Beginner

Interview Question

How can we set priority of test cases in TestNG?

Use the priority parameter in @Test annotation to control test execution order. Lower priority value = runs first. Default priority is 0.

Answer

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 valueExecution order
-11st
0 (default)2nd
13rd
24th

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:

  • priority controls execution order (lower = earlier)
  • Default priority = 0 when not specified
  • Tests with lower priority run before tests with higher priority
  • Combine with dependsOnMethods for more explicit control

Follow AutomateQA

Related Topics