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.
You have two options:
Your annotation transformer would test the condition and then override the @Test annotation to add the attribute "enabled=false" if the condition is not satisfied.
There are two ways that I know of that allow you the control of "disabling" tests in TestNG.
The differentiation that is very important to note is that SkipException will break out off all subsequent tests while implmenting IAnnotationTransformer uses Reflection to disbale individual tests, based on a condition that you specify. I will explain both SkipException and IAnnotationTransfomer.
SKIP Exception example
IAnnotationTransformer example
A bit more complicated but the idea behind it is a concept known as Reflection.
Wiki - http://en.wikipedia.org/wiki/Reflection_(computer_programming)
First implement the IAnnotation interface, save this in a *.java file.
Then in you test suite java file do the following in the @BeforeClass function
One last step is to ensure that you add a listener in your build.xml file. Mine ended up looking like this, this is just a single line from the build.xml:
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:
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.
Throwing a
SkipException
in a method annotated with@BeforeMethod
did not work for me because it skipped all the remaining tests of my test suite with no regards if aSkipException
were thrown for those tests.I did not investigate it thoroughly but I found another way : using the
dependsOnMethods
attribute on the@Test
annotation: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.
You can use this example: example