</>

Technology

TestNG

Difficulty

Beginner

Interview Question

How can we make one test method dependent on another using TestNG?

Answer

Test Method Dependencies in TestNG

TestNG''s dependsOnMethods allows you to define execution dependencies between test methods — a dependent test runs only after its dependency passes.

Basic dependency:

Java
@Test
public void loginTest() {
    System.out.println("Login test executed");
}

@Test(dependsOnMethods = { "loginTest" })
public void dashboardTest() {
    System.out.println("Dashboard test — runs only if loginTest passed");
}

Multiple dependencies:

Java
@Test(dependsOnMethods = { "loginTest", "verifyHomePageTest" })
public void checkoutTest() {
    System.out.println("Runs only after both loginTest and verifyHomePageTest pass");
}

What happens if the dependency fails?

  • The dependent test is skipped (not failed)
  • TestNG marks it as SKIP in the report
  • To force it to always run regardless: add alwaysRun = true
Java
@Test
public void loginTest() {
    Assert.fail("Login failed!");  // This fails
}

@Test(dependsOnMethods = { "loginTest" })
public void dashboardTest() {
    // This is SKIPPED because loginTest failed
}

dependsOnGroups:

Java
@Test(groups = "login")
public void loginTest() { }

@Test(dependsOnGroups = "login")
public void dashboardTest() { }

Real-world use case:

Java
@Test(priority = 1)
public void openBrowser() { driver = new ChromeDriver(); }

@Test(priority = 2, dependsOnMethods = "openBrowser")
public void navigateToURL() { driver.get("https://example.com"); }

@Test(priority = 3, dependsOnMethods = "navigateToURL")
public void verifyTitle() {
    Assert.assertEquals(driver.getTitle(), "Example Domain");
}

@Test(priority = 4, dependsOnMethods = "verifyTitle")
public void closeBrowser() { driver.quit(); }

Key points:

  • dependsOnMethods = { "methodName" } — exact method name as string
  • Dependent test is skipped (not failed) when dependency fails
  • Chain multiple methods: dependsOnMethods = { "m1", "m2" }
  • Use dependsOnGroups for group-level dependencies

Follow AutomateQA

Related Topics