简体   繁体   English

TestNG-阅读自定义注释详细信息

[英]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 . 尝试的解决方案:使用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. 内循环为每个测试类触发近n*n (方法数量)次。 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 ie generating report by reading custom annotation details from all test methods from all suites. 因为我是TestNG框架的新手,所以想知道更好的解决方案来满足我的要求,即通过从所有套件的所有测试方法中读取自定义注释详细信息来生成报告。

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 我正在使用截至今天(即7.0.0-beta3的最新版本的TestNG,并使用Java8流

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 {}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM