覆盖某些测试的 TestNG 注释

Overriding TestNG annotation for certain test

问题来了

我有一个 class,它有一个 @AfterMethod 方法,该方法适用于我的所有测试方法,除了两个测试(业务案例是它删除了我不想在每次测试后删除的内容方法)。有没有办法忽略特定测试方法的@afterMethod?

我有一个解决方案,但它不是那么优雅,任何其他的想法都会受到高度赞赏。

一种方法是让子 class 扩展父 class,在 class 中我可以覆盖 @AfterMethod,但我更愿意将所有测试放在同一个地方。

最简单的方法如下:

  • 定义自定义注解,使用时声明需要跳过特定测试方法的配置。
  • 使用此新注释注释要跳过配置的所有 @Test 方法。
  • 在你的配置方法中,检查传入的方法是否有这个注解,如果有则跳过执行。

下面的示例显示了所有这些操作。

指示要跳过配置方法的标记注释。

import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

@Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
@Target({METHOD, TYPE})
public @interface SkipConfiguration {

}

样本测试class

import java.lang.reflect.Method;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;

public class TestClassSample {

  @Test
  @SkipConfiguration
  public void foo() {}

  @Test
  public void bar() {}

  @AfterMethod
  public void teardown(Method method) {
    SkipConfiguration skip = method.getAnnotation(SkipConfiguration.class);
    if (skip != null) {
      System.err.println("Skipping tear down for " + method.getName());
      return;
    }
    System.err.println("Running tear down for " + method.getName());
  }
}