skc
skc

Reputation: 65

TestNG - Read custom annotation details

Requirement: Read custom annotation details and generate report for all test classes of all suites.

Tried Solution: Implemented custom listener using ITestListener. But don't see direct way to get custom annotation details used as part of test methods apart from below way.

@Override
public void onStart(ITestContext context) {
    ITestNGMethod[] testNGMethods = context.getAllTestMethods();
    for (ITestNGMethod testNgmethod : testNGMethods) {
        Method[] methods = testNgmethod.getRealClass().getDeclaredMethods();
        for (Method method : methods) {
            if (method.isAnnotationPresent(MyCustomAnnotation.class)) {
                //Get required info
            }
        }
    }
}

Inner loop triggers almost n*n(number of methods) times for each test class. I can control it by adding conditions.

As I'm new bee to TestNG framework, would like to know the better solution to achieve my requirement i.e. generating report by reading custom annotation details from all test methods from all suites.

Upvotes: 2

Views: 1834

Answers (1)

Krishnan Mahadevan
Krishnan Mahadevan

Reputation: 14736

Here's how you do it.

I am using the latest released version of TestNG as of today viz., 7.0.0-beta3 and using Java8 streams

import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestNGMethod;

public class MyListener implements ITestListener {

  @Override
  public void onStart(ITestContext context) {
    List<ITestNGMethod> methodsWithCustomAnnotation =
        Arrays.stream(context.getAllTestMethods())
            .filter(
                iTestNGMethod ->
                    iTestNGMethod
                            .getConstructorOrMethod()
                            .getMethod()
                            .getAnnotation(MyCustomAnnotation.class)
                        != null)
            .collect(Collectors.toList());
  }

  @Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
  @Target({METHOD, TYPE})
  public static @interface MyCustomAnnotation {}
}

Upvotes: 2

Related Questions