user1293962
user1293962

Reputation: 496

TestNG method "enabled" programmatically

Is there a way to set the "enabled" attribute for a @Test programmatically?

Something like defining a boolean variable in the @BeforeClass and check it via enabled?

The use case is this: The same tester tests several classes, but not all classes implement all methods, so the missing methods should not be skipped.

The tester would be something like

public abstract class MegaTester {

    @Test
    public void test1() {
    ...
    }

     @Test
     public void test2() {
     ...
     }

     @Test
     public void test3() {
     ...
     }
 }

 public class ATest extends MegaTester {
     @Test
     public void test1() {
     // my own implementation of test1
     }

     // test2 from MegaTester will be called here

     // I don't implement test3, but how do I indicate I don't want it ran from MegaTester?
 }

Thanks

Upvotes: 0

Views: 1892

Answers (3)

niharika_neo
niharika_neo

Reputation: 8531

Refer Here for Iannotationtransformer in testng and implement the transform method to change enabled to false at runtime.

Upvotes: 1

Nathan Merrill
Nathan Merrill

Reputation: 8386

I don't completely understand your need...but if you want to SKIP a function based on its name/class/group/other data you can set up a TestNG Listener, and have it run before each @Test.

The listener gives you access to all of the data passed in the @Test() annotation, the function name/class, and if you want to skip it, you can throw a SkipException to skip the test.

However, if you want to run X test when I run class A (and X test is not in class A)...that's not possible, unless you call the function manually, or you put that separate test in your TestNG.xml.

Upvotes: 0

Bob Dalgleish
Bob Dalgleish

Reputation: 8227

Do you need to test for the absence of the method? As in, use Java reflection to ensure that the method does not exist? Then you need to have test2() and test3() defined.

Otherwise you can just have an empty body. The test will succeed, which it should as not performing an action is built in to the process. I'm not sure what you are trying to avoid by not having SKIP in your test report. There are any number of valid reasons for skipping tests, and you have given one of them.

If ATest only tests a class that does not implement test3() then use @Test(enabled=false) in its definition. That way, TestNG will never call test3().

Here is how I would redo what you have proposed:

public abstract class MegaTester {

    @Test
    public void test1() {
    ...
    }

     @Test
     public void test2() {
     ...
     }

     @Test
     public void test3() {
     ...
     }
 }

 public class ATest extends MegaTester {
     @Test
     public void test1() {
     // my own implementation of test1
     }

     // test2 from MegaTester will be called here

     @Test(enabled=false)
     public void test3() {}
 }

Upvotes: 0

Related Questions