Search code examples
testngtestng.xml

TestNg IAnnotationTransformer listener on the class level


I have this requirement to have an IAnnotationTransformer for manipulating the @Test annotation during runtime. Also i want to define this annotation on the class level instead of the TestNG XML.

@Listeners(MyAnnotationTransformer.class)
public class TestClass {
   ...
}

MyAnnotationTransformer.java:

public class MyAnnotationTransformer implements IAnnotationTransformer {

    public void transform(ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) {

        System.out.println("Gotcha!!");
    }
}

The problem is the MyAnnotationTransformer's transform method is not called during execution.

However, if I provide the MyAnnotationTransformer Listener at the XML level, this is successful.

<listeners>
        <listener class-name="com.debugger89.testng.MyAnnotationTransformer" />
</listeners>

The official documentation does not mention any restriction like this. Is this a bug? Using TestNG version 7.4.0


Solution

  • Take a look at javadoc:

    https://javadoc.io/doc/org.testng/testng/latest/org/testng/annotations/Listeners.html

    Any class that implements the interface ITestNGListener is allowed, except IAnnotationTransformer which need to be defined in XML since they have to be known before we even start looking for annotations.

    IAnnotationTransformer can be defined

    • in XML

    • via command line: java org.testng.TestNG -listener MyAnnotationTransformer testng.xml

    • programmatically

      TestNG testNg = new TestNG();
      testNg.addListener(new MyAnnotationTransformer());
      

    See also https://github.com/cbeust/testng/issues/446