我有一个布尔虚拟机参数,一旦它为真,我想从执行/和测试报告中排除一组预/后检查。
作为第一种方法,我开始引入新的注释
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ExcludeFromReport {}
我创建了一个 Transformer 来拦截用 @ExcludeFromReport 注释的方法
public class ExcludeFromReportTransformer implements IAnnotationTransformer {
private static boolean isaBoolean(Method testMethod) {
return testMethod != null && testMethod.isAnnotationPresent(ExcludeFromReport.class);
}
@Override
public void transform(ITestAnnotation annotation, Class testClass, java.lang.reflect.Constructor testConstructor,
java.lang.reflect.Method testMethod) {
if (isMethodExcluded(testMethod)) {
annotation.setEnabled(false);
}
}
private boolean isMethodExcluded(Method testMethod) {
Log.warn("Check whether the method is excluded or not !");
boolean isExcluded = isaBoolean(testMethod);
Log.warn(String.format("Method = %s is excluded + %s", testMethod.getName(), isExcluded));
return isExcluded;
}
}
在我的测试类中,我用注释注释了测试方法和配置方法 @ExcludeFromReport,仅排除了测试方法,@BeforeTest方法已被执行。
public class MyTestSuite {
@BeforeTest
@ExcludeFromReport
public void testCase1() {
Log.info("testCase1");
}
@Test
@ExcludeFromReport
public void testCase2() {
Log.info("testCase2");
}
@Test
public void testCase3() {
Log.info("testCase3");
}
}
有什么想法吗?
首先,我们需要使用更广泛的 IAnnotationTransformer 接口,它允许转换多个 TestNG 注释,包括 @Test、@BeforeTest 等。
修改变压器以处理@BeforeTest、@AfterTest等:
import org.testng.IAnnotationTransformer;
import org.testng.annotations.ITestAnnotation;
import org.testng.annotations.IConfigurationAnnotation;
public class ExcludeFromReportTransformer implements IAnnotationTransformer {
private static boolean isaBoolean(Method testMethod) {
return testMethod != null && testMethod.isAnnotationPresent(ExcludeFromReport.class);
}
@Override
public void transform(ITestAnnotation annotation, Class testClass, java.lang.reflect.Constructor testConstructor,
java.lang.reflect.Method testMethod) {
if (isMethodExcluded(testMethod)) {
annotation.setEnabled(false);
}
}
public void transform(IConfigurationAnnotation annotation, Class testClass,
java.lang.reflect.Constructor testConstructor,
java.lang.reflect.Method testMethod) {
if (isMethodExcluded(testMethod)) {
annotation.setEnabled(false);
}
}
private boolean isMethodExcluded(Method testMethod) {
Log.warn("Check whether the method is excluded or not !");
boolean isExcluded = isaBoolean(testMethod);
Log.warn(String.format("Method = %s is excluded + %s", testMethod.getName(), isExcluded));
return isExcluded;
}
}
确保将变压器作为侦听器添加到您的套件中,这个解决方案肯定适合您。