如何使用testNG在测试报告中记录@Test方法的详细信息

How to log the @Test method details in testreport using testNG

我有一个 class 并且它包含一个 @Test 方法 (sampleTest1)。在那个方法中,我有 4 个来自其他 class 的 @Test 方法调用。当我通过 TestNG 运行 我的测试用例时,它仅在输出控制台中记录主要测试方法,并表示 1 个测试方法已通过。

如何记录子class文件中定义的所有4个测试方法?

有人能帮帮我吗

谢谢, 萨西

TestNG 的测试用例之间不能有父子关系,如果您尝试从父测试调用它们,它们将执行,但它们不会成为报告的一部分,如果它们失败,您可能没有任何线索。

Annotation Transformers Approach

如果您想 运行 基于某些条件的方法,那么您可能需要查看 Annotation Transformers

您需要通过实现 IAnnotationTransformer 接口来创建 class。检查转换方法中的条件,将 Enable 属性 设置为 true 或 false 以禁用 @Test testcase.

public class MyTransformer implements IAnnotationTransformer {
  private MyParentClass parent;
  public MyTransformer(MyParentClass parent){
      this.parent = parent;
  }
  public void transform(ITest annotation, Class testClass,
      Constructor testConstructor, Method testMethod)
  {
    if (checkConditionForMethod(testMethod.getName())) {
      annotation.setEnabled(false);
    }
  }
  public boolean checkConditionForMethod(String methodName){
       return parent.isValidSwitchForMethod(methodName);
  }
}

您以编程方式添加注释转换器:

TestNG tng = new TestNG();
tng.setAnnotationTransformer(new MyTransformer(parentClassInstance));

Inner classes approach

嵌套测试用例的其他方法是为您的父级 class 创建内部 class,然后在内部 class 中定义测试用例,但没有任何条件.

例如,如果您低于 class 结构:

TestClassParent [Testcase1Parent] [Testcase2Parent]
  |_ TestSubClass1 [Testcase1Sub1] [Testcase1Sub1]
  |_ TestSubClass2 [Testcase1Sub2] [Testcase2Sub2]

那么执行的顺序是这样的:你需要根据执行的顺序来定义你的测试用例来实现你的目标。

Testcase1Sub1
Testcase2Sub1
Testcase1Sub2
Testcase2Sub2
Testcase1Parent
Testcase2Parent

Testng 只记录它自己调用的@Test 方法。但是如果你是通过创建testclass的对象来调用的。它不会将其记录为单独的测试。

所以你可以做的是让 testng 调用它们并通过使用 dependsongroups 和 dependsonmethods 来维护执行流程。但是请注意,一旦你使用依赖于组,testng 将不再保留你的测试 class 顺序。