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

问题描述 投票:0回答:1

要求:阅读自定义注释详细信息并为所有套件的所有测试类生成报告。

尝试的解决方案:使用ITestListener实现自定义侦听器。但是,除了以下方式之外,不要直接看到将自定义注释细节用作测试方法的一部分。

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

内部循环触发每个测试类几乎n*n(方法的数量)次。我可以通过添加条件来控制它。

由于我是TestNG框架的新手,想知道更好的解决方案来实现我的要求,即通过从所有套件的所有测试方法中读取自定义注释详细信息来生成报告。

java testng
1个回答
1
投票

这是你如何做到的。

我正在使用最新发布的TestNG版本,即今天,7.0.0-beta3和使用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 {}
}
© www.soinside.com 2019 - 2024. All rights reserved.