</>

Technology

TestNG

Difficulty

Intermediate

Interview Question

How can we make sure a test method runs even if the methods it depends on fail or get skipped?

Set alwaysRun=true in @Test annotation to force a test method to execute regardless of whether its dependencies passed, failed, or were skipped.

Answer

alwaysRun Attribute in TestNG

By default, if a method listed in dependsOnMethods fails, the dependent test is skipped. Setting alwaysRun = true overrides this — the test runs regardless of what happened to its dependencies.

Without alwaysRun (default behavior):

Java
@Test
public void parentTest() {
    Assert.fail("Failed test");  // This FAILS
}

@Test(dependsOnMethods = {"parentTest"})
public void dependentTest() {
    System.out.println("This is SKIPPED because parentTest failed");
}

With alwaysRun = true:

Java
@Test
public void parentTest() {
    Assert.fail("Failed test");  // This FAILS
}

@Test(dependsOnMethods = {"parentTest"}, alwaysRun = true)
public void dependentTest() {
    System.out.println("Running even if parent test failed");
    // This RUNS despite parentTest failing
}

Report difference:

ScenarioparentTestdependentTest
Without alwaysRunFAILEDSKIPPED
With alwaysRun = trueFAILEDRUNS (passes or fails on its own)

Practical use case — cleanup after failure:

Java
@Test
public void createUserTest() {
    // Create a user — might fail
    Assert.assertTrue(createUser("testUser"), "User creation failed");
}

@Test(dependsOnMethods = {"createUserTest"}, alwaysRun = true)
public void deleteUserTest() {
    // ALWAYS delete the user to clean up, even if creation failed
    deleteUser("testUser");
}

alwaysRun with groups:

Java
@Test(dependsOnGroups = {"login"}, alwaysRun = true)
public void teardownTest() {
    // Always runs cleanup even if login group tests fail
    driver.quit();
}

Key points:

  • Without alwaysRun: dependent test is SKIPPED when dependency fails
  • With alwaysRun = true: dependent test ALWAYS RUNS regardless
  • Useful for cleanup tests that must run even after failure
  • Removing alwaysRun=true from @AfterClass/@AfterMethod can prevent cleanup

Follow AutomateQA

Related Topics