Skip to content

Instantly share code, notes, and snippets.

@LenarBad
Last active November 20, 2020 08:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LenarBad/23c2da1e5069adf5831fc268b0a06f9a to your computer and use it in GitHub Desktop.
Save LenarBad/23c2da1e5069adf5831fc268b0a06f9a to your computer and use it in GitHub Desktop.
How to skip TestNG tests based on condition using IInvokedMethodListener
@Listeners(value = ConditionalSkipTestAnalyzer.class)
public class ExampleConditionalSkippingTest {
@NonProduction
@Test
public void test1() { }
@ProductionOnly
@Test
public void test2() { }
@HappyFriday
@Test
public void test3() { }
@HateRain
@Test
public void test4() { }
@ProductionOnly
@HappyFriday
@Test
public void test5() { }
}
public class ConditionalSkipTestAnalyzer implements IInvokedMethodListener {
public void beforeInvocation(IInvokedMethod invokedMethod, ITestResult result) {
Method method = result.getMethod().getConstructorOrMethod().getMethod();
if (method == null) {
return;
}
if (method.isAnnotationPresent(NonProduction.class) && EnvironmentUtils.isProduction()) {
throw new SkipException("These Tests shouldn't be run in Production");
}
if (method.isAnnotationPresent(ProductionOnly.class) && !EnvironmentUtils.isProduction()) {
throw new SkipException("These Tests should be run in Production only");
}
if (method.isAnnotationPresent(HappyFriday.class) && TimeAndDatesUtils.isFridayToday()) {
throw new SkipException("These Tests shouldn't be run on Friday");
}
if (method.isAnnotationPresent(HateRain.class) && WheatherUtils.isItRaining()) {
throw new SkipException("These Tests shouldn't be run in case of rain");
}
return;
}
public void afterInvocation(IInvokedMethod method, ITestResult testResult) {
}
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ProductionOnly {
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ProductionOnly {
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ProductionOnly {
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ProductionOnly {
}
@LenarBad
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment