Blog
What is TestNG dependsOnMethods?
h2>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");
}