0
0
Selenium Javatesting~5 mins

Dependency between tests in Selenium Java

Choose your learning style9 modes available
Introduction

Sometimes one test needs another test to run first because it depends on its result. This helps keep tests organized and avoid repeating steps.

When you need to log in before testing other features.
When creating data in one test that another test will use.
When testing a sequence of actions that must happen in order.
When you want to skip tests if a previous important test fails.
Syntax
Selenium Java
@Test(dependsOnMethods = {"methodName"})
public void testMethod() {
    // test code here
}

Use the dependsOnMethods attribute in the @Test annotation to specify dependencies.

The dependent test will be skipped if the method it depends on fails.

Examples
The dashboardTest runs only if loginTest passes.
Selenium Java
@Test
public void loginTest() {
    // login steps
}

@Test(dependsOnMethods = {"loginTest"})
public void dashboardTest() {
    // test dashboard after login
}
deleteUser depends on createUser to ensure the user exists before deletion.
Selenium Java
@Test
public void createUser() {
    // create user steps
}

@Test(dependsOnMethods = {"createUser"})
public void deleteUser() {
    // delete user steps
}
Sample Program

This test class has three tests. Each test depends on the previous one. If openHomePage fails, the others will be skipped.

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

public class DependencyTest {

    @Test
    public void openHomePage() {
        System.out.println("Opening home page");
        Assert.assertTrue(true);
    }

    @Test(dependsOnMethods = {"openHomePage"})
    public void login() {
        System.out.println("Logging in");
        Assert.assertTrue(true);
    }

    @Test(dependsOnMethods = {"login"})
    public void accessDashboard() {
        System.out.println("Accessing dashboard");
        Assert.assertTrue(true);
    }
}
OutputSuccess
Important Notes

Dependencies help avoid repeating setup steps in each test.

Use dependencies carefully to keep tests independent when possible.

TestNG will skip dependent tests if the test they depend on fails.

Summary

Use dependsOnMethods to link tests that must run in order.

Dependent tests skip if the test they rely on fails.

Helps organize tests that need previous steps done first.