出于好奇,进行了一些头脑风暴,并提出了以下使用 v6.14.2 测试的解决方法。我个人更喜欢第一个,更简洁、更优雅、更灵活、更易于维护和扩展。
上下文
import org.testng.annotations.Test;
import static org.testng.Assert.assertTrue;
public class MyTest {
@Test
public void shouldRun() {
assertTrue(true);
}
@Test
public void shouldNotRun() {
assertTrue(true);
}
@Test
public void shouldNotRunEither() {
assertTrue(true);
}
}
1) 使用侦听器 - 创建 TestListenerAdapter 和注释以跳过具有特定名称的方法:灵活、清晰、易于重用和识别以删除。唯一的缺点是您必须注意拼写错误的方法名称。
注释
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface SkipMethods {
String[] value() default {};
}
TestListenerAdapter
import org.testng.ITestResult;
import org.testng.SkipException;
import org.testng.TestListenerAdapter;
public class TestSkippingListener extends TestListenerAdapter {
@Override
public void onTestStart(ITestResult result) {
// get the skip annotation
SkipMethods skipAnnotation = result.getMethod().getInstance().getClass().getAnnotation(SkipMethods.class);
// if the annotation exists
if (skipAnnotation != null) {
for (String skippableMethod : skipAnnotation.value()) {
// and defines the current method as skippable
if (skippableMethod.equals(result.getMethod().getMethodName())) {
// skip it
throw new SkipException("Method [" + skippableMethod + "] marked for skipping");
}
}
}
}
}
测试子类
import org.testng.annotations.Listeners;
// use listener
@Listeners(TestSkippingListener.class)
// define what methods to skip
@SkipMethods({"shouldNotRun", "shouldNotRunEither"})
public class MyTestSkippingInheritedMethods extends MyTest {
}
结果
2) 覆盖超类中的方法并抛出SkipException:很清楚,没有错字的可能性,但不可重用,不易维护并引入无用代码:
import org.testng.SkipException;
public class MyTestSkippingInheritedMethods extends MyTest {
@Override
public void shouldNotRun() {
throw new SkipException("Skipped");
}
@Override
public void shouldNotRunEither() {
throw new SkipException("Skipped");
}
}
结果