Custom annotations help you add extra information to your test code in a clear and reusable way.
Custom annotations in Selenium Java
import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) public @interface YourAnnotation { String value() default ""; int priority() default 1; }
Use @Retention(RetentionPolicy.RUNTIME) to keep the annotation available during test execution.
Define annotation elements like methods with default values for flexibility.
import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) public @interface TestInfo { String author(); String category() default "General"; }
@TestInfo(author = "Alice", category = "Smoke") public void testLogin() { // test code }
import java.lang.reflect.Method; Method method = MyTestClass.class.getMethod("testLogin"); TestInfo info = method.getAnnotation(TestInfo.class); System.out.println("Author: " + info.author());
This program defines a custom annotation @TestInfo with author and category. It applies it to a test method and reads the annotation values using reflection before running the test.
import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.reflect.Method; @Retention(RetentionPolicy.RUNTIME) @interface TestInfo { String author(); String category() default "General"; } public class CustomAnnotationExample { @TestInfo(author = "Bob", category = "Regression") public void testSearch() { System.out.println("Running testSearch"); } public static void main(String[] args) throws Exception { Method method = CustomAnnotationExample.class.getMethod("testSearch"); TestInfo info = method.getAnnotation(TestInfo.class); System.out.println("Author: " + info.author()); System.out.println("Category: " + info.category()); CustomAnnotationExample example = new CustomAnnotationExample(); example.testSearch(); } }
Custom annotations must be retained at runtime to be accessible during test execution.
Use reflection carefully; it can slow down tests if overused.
Annotations help keep test code clean and organized by separating metadata from logic.
Custom annotations add reusable metadata to your tests.
They are defined with @interface and retained at runtime.
You can read annotation data using Java reflection to control test behavior.