TestNG: accessing a Custom Annotation

TestNG: accessing a Custom Annotation

30 August 2013

Access a custom annotation from test setup and teardown methods. Ensure to add a @Retention annotation and persist at runtime by setting the RetentionPolicy to RUNTIME. Without it you won't be able to get the annotation during test runtime.

Example:

@Target(value=ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation{
}

public class ATest {
    @BeforeMethod
    public void before(Method testMethod) {
        if(method.getAnnotation(@MyAnnotation.class)!=null) {
            //do stuff
        }
    }

    @AfterMethod
    public void after(Method testMethod) {

    }

    @Test @MyAnnotation
    public myTest() {
    }
}
Java Testing TestNG