Modify Annotations Programmatically Using TestNG IAnnotationTransformer2

Among the sevral listeners provided by TestNG, I find IAnnotationTransformer2 listener as one of the coolest ones. Th reason being, it allows to modify or change the annotations through code by changing the annotations parameters, instead of declarative approach through XML. It works at both levels viz. annotations on classes and methods. Read more about other annotation transformers here.

 

A simple Usecase

A scenario where the IAnnotationTransformer2 listener can be used is when you want run certain methods dynamically based on some condition. For instance, there might be a scenario when a method should be executed only when the previous test method has produced certain output(more like changed some value somewhere). In that case the enabled param for a test annotation can be set to false and that will cause the TestNG to skip the method. Same can be applied for the whole class when you want to skip the whole class.

Below is how to implement a basic version of above usecase:

Annotation Transformer
Annotation Transformer

Now all we have to do is tell TestNG to use this class as a listener. This can be done annotation in code or through XML. I preferred XML:

Register Listener
Register Listener

Note that if same annotations are present on class and methods, annotations at method level take precedence. So if the enabled parameter is to true on method but is false on class, the true value from the method will take precedence and the class will execute.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s