Last active
November 20, 2020 08:49
-
-
Save LenarBad/23c2da1e5069adf5831fc268b0a06f9a to your computer and use it in GitHub Desktop.
How to skip TestNG tests based on condition using IInvokedMethodListener
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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 { | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See also How to skip TestNG tests based on condition