TestNG @AfterMethod 绑定到当前 class 的方法

TestNG @AfterMethod bind to methods of current class

好吧,我有点困惑。

public class GroupDemo {

   @Test()
   public void test1() {
        System.out.println("test1");
   }
}

public class GroupDemoChild extends GroupDemo{

   @Test
   public void atest(){
       System.out.println("atest");
   }

   @AfterMethod
   public void after() {
       System.out.println("after method");
   }
}

这里合乎逻辑的是:

test1
atest
after method

然而我得到:

test1
after method
atest
after method

因此 after() 被调用了两次。

如何仅在声明 class 方法后才 运行?

TestNG = 6.8.5; Java = 1.7

@AfterMethod
public void after(Method method) {
    if(method.getDeclaringClass() == this.getClass()) {
        System.out.println("after method"); 
    }
}

是一种快速而肮脏的解决方案。但是对于普通人我们还能有什么吗?

实际上当前行为是:

  • test1()
  • 之后()
  • atest()
  • 之后()
  • test1()

因为 @AfterMethod 在 'current' class 层次结构中的每个 @Test 方法之后运行,如果你再次包含 class 而没有它,它不会被执行。

解决方案是不使用 extends GroupDemo 并创建更多 specific/generic classes(基本上重构您的测试 class 层次结构)。

您还可以使用 @AfterMethod 中的一些属性来更好地控制流量 (alwaysRun, groups, etc.)。 http://testng.org/javadoc/org/testng/annotations/AfterMethod.html

在Testng中,@AfterMethod会在每个@Test方法后执行。

使用@AfterTest,这将在所有@Test执行完后执行。

您还可以利用 IInvokedMethodListener 接口的自定义实现以及一些自定义注释。类似于:

@Listeners({ com.somepackage.MethodInvocationListener.class })
public class GroupDemoChild extends GroupDemo{

   @Test
   @AfterEd
   public void atest(){
       System.out.println("atest");
   }
}

public class MethodInvocationListener implements IInvokedMethodListener {
    @Override
    public void beforeInvocation(IInvokedMethod iInvokedMethod, ITestResult iTestResult) {
        // doNothing
    }

    @Override
    public void afterInvocation(IInvokedMethod iInvokedMethod, ITestResult iTestResult) {
        if (iInvokedMethod.getTestMethod().getConstructorOrMethod()
                .getMethod().getAnnotation(AfterEd.class) != null) {
                System.out.println("after method");
        }
    }
}