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:
- ✓Test method stops executing at the
throwline - ✓Test is marked as SKIPPED (yellow) in the TestNG report
- ✓
@AfterMethodstill runs (cleanup still happens) - ✓
dependsOnMethodstests are also skipped
SkipException vs dependsOnMethods:
| Approach | When to use |
|---|---|
SkipException | Runtime condition — data, environment, browser |
dependsOnMethods | Structural 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
- ✓
@AfterMethodcleanup still executes after a skip
