0
0
Selenium Javatesting~5 mins

Why TestNG structures test execution in Selenium Java

Choose your learning style9 modes available
Introduction

TestNG organizes how tests run to make sure they happen in the right order and work well together. This helps find problems faster and keeps tests clear.

When you want to run multiple tests in a specific order.
When tests depend on each other and must run one after another.
When you want to group tests by features or priority.
When you want to run tests in parallel to save time.
When you want clear reports showing which tests passed or failed.
Syntax
Selenium Java
import org.testng.annotations.Test;

public class SampleTest {

    @Test(priority = 1)
    public void firstTest() {
        // test code here
    }

    @Test(priority = 2, dependsOnMethods = {"firstTest"})
    public void secondTest() {
        // test code here
    }
}

@Test marks a method as a test.

priority controls the order tests run; lower numbers run first.

Examples
This test runs first because it has priority 1.
Selenium Java
@Test(priority = 1)
public void loginTest() {
    // test login
}
This test runs after loginTest because it depends on it.
Selenium Java
@Test(priority = 2, dependsOnMethods = {"loginTest"})
public void dashboardTest() {
    // test dashboard after login
}
This test belongs to the 'smoke' group for easy selection.
Selenium Java
@Test(groups = {"smoke"})
public void quickCheck() {
    // quick test
}
Sample Program

This test class runs three tests in order: openPage, checkTitle, and closePage. Each test prints a message and checks a simple condition. The dependsOnMethods ensure the order and that tests only run if the previous ones pass.

Selenium Java
import org.testng.Assert;
import org.testng.annotations.Test;

public class SimpleTest {

    @Test(priority = 1)
    public void openPage() {
        System.out.println("Opening page");
        Assert.assertTrue(true);
    }

    @Test(priority = 2, dependsOnMethods = {"openPage"})
    public void checkTitle() {
        System.out.println("Checking title");
        Assert.assertEquals("Home", "Home");
    }

    @Test(priority = 3, dependsOnMethods = {"checkTitle"})
    public void closePage() {
        System.out.println("Closing page");
        Assert.assertTrue(true);
    }
}
OutputSuccess
Important Notes

TestNG helps avoid running tests that depend on failed tests.

Using priority and dependsOnMethods keeps tests organized and reliable.

TestNG generates reports that show test order and results clearly.

Summary

TestNG structures test execution to control order and dependencies.

This helps tests run smoothly and find problems faster.

Using TestNG features like priority and dependsOnMethods improves test clarity.