</>

Technology

TestNG

Difficulty

Intermediate

Interview Question

How can we skip a test case conditionally in TestNG?

Throw SkipException inside your test method to conditionally skip it. The test is marked as skipped and remaining code in that method does not execute.

Answer

Conditionally Skipping a Test Case in TestNG

Use throw new SkipException("reason") inside your test to conditionally skip it based on runtime conditions.

Basic example:

Java
import org.testng.SkipException;
import org.testng.annotations.Test;

public class ConditionalSkipTest {

    @Test
    public void testMethod() {
        boolean conditionToCheckForSkippingTest = true;

        if (conditionToCheckForSkippingTest) {
            throw new SkipException("Skipping the test");
            // Any code after this line is NOT executed
        }
        // Test logic here — only reached if condition is false
        System.out.println("Running test logic");
    }
}

Real-world conditional skip:

Java
@Test
public void featureTest() {
    String environment = System.getProperty("env", "staging");

    // Skip this test in production environment
    if (environment.equals("production")) {
        throw new SkipException("Skipping in production — destructive test");
    }

    // Test runs only in staging/dev
    driver.findElement(By.id("deleteAllBtn")).click();
}

Skip based on browser:

Java
@Test
public void ie11SpecificTest() {
    String browser = System.getProperty("browser", "chrome");

    if (!browser.equalsIgnoreCase("ie")) {
        throw new SkipException("This test is only for IE browser");
    }

    // IE-specific test logic
}

What happens when SkipException is thrown:

  1. Test method stops executing at the throw line
  2. Test is marked as SKIPPED (yellow) in the TestNG report
  3. @AfterMethod still runs (cleanup still happens)
  4. dependsOnMethods tests are also skipped

SkipException vs dependsOnMethods:

ApproachWhen to use
SkipExceptionRuntime condition — data, environment, browser
dependsOnMethodsStructural dependency — test A must pass first

Key points:

  • throw new SkipException("message") marks test as SKIPPED in report
  • Any code after the throw is not executed
  • The test is not counted as a failure — it''s explicitly skipped
  • @AfterMethod cleanup still executes after a skip

Follow AutomateQA

Related Topics