根据条件和测试 class 注释禁用 TestNG 测试

Disable TestNG tests based on condition and test class annotation

我有一个测试套件,有时需要在生产环境中使用,但由于技术细节,无法 运行 对其进行一些测试。我的想法是使用自定义注释来注释此类测试 classes,然后如果我 运行ning 反对生产,则禁用其中的测试方法。像这样:

    @DisableOnProd
    class SomeTestClass {   
    @BeforeMethod
    void setUp(){
        ...
    }   
    @Test
    void test() {
        ...
    }   
}

我可以像这样实现 IAnnotationTransformer2,但它会禁用所有测试方法:

    @Override
    public void transform(ITestAnnotation iTestAnnotation, Class aClass, Constructor constructor, Method method) {
    if (method.isAnnotationPresent(Test.class) || method.isAnnotationPresent(BeforeMethod.class)) {
        iTestAnnotation.setEnabled(false);
    }
}

}

是否有任何方法可以获取测试 class 注释来检查条件,或者是否可以通过其他解决方案获得相同的结果?

您可以使用 testng 侦听器 onTestStart,条件如下:

public class TestListener extends TestListenerAdapter {



      public void onTestStart(ITestResult arg0) {

            super.onTestStart(arg0);



            if (condition)  {

                  throw new SkipException("Testing skip.");

            }



      }

}

或者可以利用有条件的Before方法

@BeforeMethod
public void checkCondition() {
  if (condition) {
    throw new SkipException("Skipping tests .");
  }
}

尝试检查 class 上的注释以及其他情况。例如:

   if(someCondition && testMethod.getDeclaringClass().isAnnotationPresent(DisableOnProd.class)) {
            iTestAnnotation.setEnabled(false);
   }

感谢您的回答,他们为我指明了正确的方向。到目前为止,我得到的最灵活的解决方案是使用实现 IMethodInterceptor:

的侦听器
public class SkipOnProductionListener implements IMethodInterceptor {

    public List<IMethodInstance> intercept(List<IMethodInstance> list, ITestContext iTestContext) {
        if (isProduction()) {
            list.removeIf(method -> method.getMethod().getRealClass().isAnnotationPresent(SkipIfOnProd.class));
            list.removeIf(method -> method.getMethod().getConstructorOrMethod().getMethod().isAnnotationPresent(SkipIfOnProd.class));
        }
        return list;
    }

    private boolean isProduction() {
        //do some env determination logic here
        return true;
    }

}

这样我可以将注释放在 class 上并跳过所有测试方法,或者只是个别方法。