我有一个测试套件,不时需要在prod环境中使用,但由于技术细节,不可能对它进行一些测试。我的想法是使用自定义注释来注释这些测试类,然后如果我正在针对prod运行,则禁用其中的测试方法。像这样的东西:
@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);
}
}
}
有没有办法让测试类注释来检查条件,或者有办法与其他解决方案获得相同的结果?
你可以使用testng监听器onTestStart,条件如下:
public class TestListener extends TestListenerAdapter {
public void onTestStart(ITestResult arg0) {
super.onTestStart(arg0);
if (condition) {
throw new SkipException("Testing skip.");
}
}
}
或者在使用某些条件的方法之前
@BeforeMethod
public void checkCondition() {
if (condition) {
throw new SkipException("Skipping tests .");
}
}
尝试检查课堂上的注释以及其他条件。例如:
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;
}
}
这样我就可以在类上放置注释并跳过所有测试方法,或者只是单个方法。