Method or Constructor level custom testng annotation implementation
Step 1: Define your METHOD scope annotation:
———————————————
package com.CustomTestNG.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface TesterInfo{
public enum PRIORITY {LOW, MEDIUM, HIGH}
PRIORITY priority() default PRIORITY.LOW;
String tester() default “Sheetal”;
}
Step 2: Custom implementation of TestNG interface “ITestListener” for processing method annotations
—————————————————————————————————-
package com.CustomTestNG.Annotation;
import java.lang.annotation.Annotation;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
public class MyTestNGAnnotation implements ITestListener {
private int sCount = 0;
@Override
public void onTestStart(ITestResult tr) {
Annotation an = tr.getMethod().getConstructorOrMethod().getMethod().getAnnotation(TesterInfo.class);
TesterInfo obj = (TesterInfo) an;
if (obj.tester().equals(“Sheetal”)) {
sCount++;
}
}
//…….. Other methods implementations
@Override
public void onFinish(ITestContext context) {
System.out.println(“Count of runs for sheetal ” + sCount);
}
}
Step 3: your TestNG Script with your annotations:
————————————————
package com.CustomTestNG.Annotation;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
import com.CustomTestNG.Annotation.TesterInfo.PRIORITY;
@Listeners(MyTestNGAnnotation.class)
public class TestNGScript {
@Test
@TesterInfo(tester=”Sheetal”, priority=PRIORITY.LOW)
public void s() {
System.out.println(“Sheetal”);
}
}
OUTPUT:
——-
[RemoteTestNG] detected TestNG version 6.14.3
Sheetal
Count of runs for sheetal 1
PASSED: s
===============================================
Default test
Tests run: 1, Failures: 0, Skips: 0
===============================================
===============================================
Default suite
Total tests run: 1, Failures: 0, Skips: 0
===============================================
0 comments