好吧,我有点困惑。
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()
被调用两次。
如何在声明类的方法之后运行它?
TestNG = 6.8.5; Java = 1.7
答案 0 :(得分:2)
您还可以使用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");
}
}
}
答案 1 :(得分:0)
@AfterMethod
public void after(Method method) {
if(method.getDeclaringClass() == this.getClass()) {
System.out.println("after method");
}
}
是一个快速而肮脏的解决方案。但是我们可以为普通人提供更多的东西吗?
答案 2 :(得分:0)
实际上目前的行为是:
因为@AfterMethod
在'当前'中的每个@Test
方法之后运行类层次结构,如果你再次包含没有它的类,它就不会被执行。
解决方案是不使用extends GroupDemo
并创建更多特定/泛型类(基本上重构您的测试类层次结构)。
您还可以使用@AfterMethod
中的一些属性来更好地控制流量(alwaysRun, groups, etc.
)。 http://testng.org/javadoc/org/testng/annotations/AfterMethod.html
答案 3 :(得分:-1)
在Testng中,@AfterMethod
将在每个@Test
方法后执行。
使用@AfterTest
,这将在所有@Test
执行完毕后执行。