BT

Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ

Topics

Choose your language

InfoQ Homepage News Annotation Transformers in TestNG: The Sweet Spot for Annotations?

Annotation Transformers in TestNG: The Sweet Spot for Annotations?

Bookmarks

In the continuing search to find the balance between XML and annotations, TestNG has introduced the concept of annotation transformers.  Conceived of by TestNG co-founder Alexandru Popescu (who is also InfoQ's Chief Architect), an annotation transformer is code that will override the behavior of annotations elsewhere in your project. This allows you to modify your annotation without using XML and without recompiling your source. You will have to recompile your annotation transformers if you change them.

Cedric Beust details the idea of annotation transformers and compares the pros and cons of XML vs annotations. His summary of XML vs annotations is:

...annotations allow you to put your configuration system close to the Java source it applies to, but changing it requires Java knowledge and a recompilation. On the other hand, XML files are usually easy to modify and they can be reread at runtime (sometimes even without relaunching your application), but they are very verbose and the edition can be error prone.

Beust refers to an idea he had back in 2004 of using XML to override annotations as something that is unlikely to take off, for good reason. Instead, TestNG 5.3 includes annotations transformers, which allow developers to programmatically override annotations, via the IAnnotationTransformer interface.  An example of their use is to override the number of times a test is invoked.  For example:

public class Mytest {
 @Test(invocationCount = 10)
 public void verify() {
 // ...
 }
}

This test annotation could be transformed to change the invocation count to a higher number:

public class MyTransformer implements IAnnotationTransformer {
 public void transform(ITest annotation, Class testClass,
 Constructor testConstructor, Method testMethod) {
 if ("verify".equals(testMethod.getName())) {
 annotation.setInvocationCount(15);
 }
 }
}

Rate this Article

Adoption
Style

BT