What is TestNG dependsOnMethods?
What is TestNG dependsOnMethods?
dependsOnMethods ensures that a test method runs only after the specified method runs successfully.
If the dependent method fails or is skipped, the depending method will also be skipped.
✅ Basic Example
import org.testng.annotations.Test;
public class LoginTest {
@Test
public void openBrowser() {
System.out.println("Browser opened");
}
@Test(dependsOnMethods = "openBrowser")
public void login() {
System.out.println("User logged in");
}
@Test(dependsOnMethods = "login")
public void verifyHomePage() {
System.out.println("Home page verified");
}
}
🔎 Execution Order
- openBrowser()
- login() (runs only if openBrowser() passes)
- verifyHomePage() (runs only if login() passes)
❌ What Happens If a Method Fails?
If openBrowser() fails:
- login() → SKIPPED
- verifyHomePage() → SKIPPED
🔹 Multiple Dependencies Example
@Test
public void startServer() {
System.out.println("Server started");
}
@Test
public void connectDatabase() {
System.out.println("Database connected");
}
@Test(dependsOnMethods = {"startServer", "connectDatabase"})
public void runTests() {
System.out.println("Tests running...");
}
Here, runTests() runs only if both methods pass.
🔹 Using alwaysRun = true
@Test(dependsOnMethods = "openBrowser", alwaysRun = true)
public void login() {
System.out.println("Login attempted even if browser failed");
}