How to disable TestNG test based on a condition

Viewed 46480

Is there currently a way to disable TestNG test based on a condition

I know you can currently disable test as so in TestNG:

@Test(enabled=false, group={"blah"})
public void testCurrency(){
...
}

I will like to disable the same test based on a condition but dont know how. something Like this:

@Test(enabled={isUk() ? false : true), group={"blah"})
public void testCurrency(){
...
}

Anyone has a clue on whether this is possible or not.

7 Answers

An easier option is to use the @BeforeMethod annotation on a method which checks your condition. If you want to skip the tests, then just throw a SkipException. Like this:

@BeforeMethod
protected void checkEnvironment() {
  if (!resourceAvailable) {
    throw new SkipException("Skipping tests because resource was not available.");
  }
}

A Third option also can be Assumption Assumptions for TestNG - When a assumption fails, TestNG will be instructed to ignore the test case and will thus not execute it.

  • Using the @Assumption annotation
  • Using AssumptionListener Using the Assumes.assumeThat(...) method

You can use this example: Conditionally Running Tests In TestNG

I prefer this annotation based way for disable/skip some tests based on environment settings. Easy to maintain and not requires any special coding technique.

  • Using the IInvokedMethodListener interface
  • Create a custom anntotation e.g.: @SkipInHeadlessMode
  • Throw SkipException
public class ConditionalSkipTestAnalyzer implements IInvokedMethodListener {
    protected static PropertiesHandler properties = new PropertiesHandler();

    @Override
    public void beforeInvocation(IInvokedMethod invokedMethod, ITestResult result) {
        Method method = result.getMethod().getConstructorOrMethod().getMethod();
        if (method == null) {
            return;
        }
        if (method.isAnnotationPresent(SkipInHeadlessMode.class)
                && properties.isHeadlessMode()) {
            throw new SkipException("These Tests shouldn't be run in HEADLESS mode!");
        }
    }

    @Override
    public void afterInvocation(IInvokedMethod iInvokedMethod, ITestResult iTestResult) {
        //Auto generated
    }
}

Check for the details: https://www.lenar.io/skip-testng-tests-based-condition-using-iinvokedmethodlistener/

SkipException: It's useful in case of we have only one @Test method in the class. Like for Data Driven Framework, I have only one Test method which need to either executed or skipped on the basis of some condition. Hence I've put the logic for checking the condition inside the @Test method and get desired result. It helped me to get the Extent Report with test case result as Pass/Fail and particular Skip as well.

Related