问题描述
在Java中,侦听器和侦听器之间的基本区别是什么?如果我同时添加两者,哪个会先被调用?
Whats the basic difference between Interceptor and Listener in java? If i add both, which will be invoked first?
推荐答案
1)IMethodInterceptor允许用户修改要执行的方法(或Test)的列表.2)IInvokedMethodListener允许用户在执行方法之前/之后执行某些操作.诸如清理或设置之类的东西.3)首先调用IMethodInterceptor,以便如果用户希望修改要执行的方法列表,则用户可以对其进行更改并将其传递给TestRunner.请参见下面的示例代码:
1) IMethodInterceptor allows user to modify the list of methods (or Test) to be executed.2) IInvokedMethodListener allows user to perform certain action before/after a method has been executed. something like clean up or setup.3) First IMethodInterceptor is called so that if user wishes to modify the list of method to be executed then a user can change it and pass it to TestRunner.Please see below example code:
package practise;
import org.testng.IInvokedMethod;
import org.testng.IInvokedMethodListener2;
import org.testng.ITestContext;
import org.testng.ITestResult;
public class InvokedMethodListener implements IInvokedMethodListener2
{
@Override
public void afterInvocation(IInvokedMethod arg0, ITestResult arg1)
{
System.out.println(Thread.currentThread().getStackTrace()[0].getMethodName());
}
@Override
public void beforeInvocation(IInvokedMethod arg0, ITestResult arg1)
{
System.out.println(Thread.currentThread().getStackTrace()[0].getMethodName());
}
@Override
public void afterInvocation(IInvokedMethod arg0, ITestResult arg1, ITestContext arg2)
{
System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName());
}
@Override
public void beforeInvocation(IInvokedMethod arg0, ITestResult arg1, ITestContext arg2)
{
System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName());
}
}
package practise;
import java.util.List;
import org.testng.IMethodInstance;
import org.testng.IMethodInterceptor;
import org.testng.ITestContext;
public class MethodInterceptor implements IMethodInterceptor
{
@Override
public List<IMethodInstance> intercept(List<IMethodInstance> arg0, ITestContext arg1)
{
System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName());
return arg0;
}
}
package practise;
import org.testng.annotations.Listeners;
@Listeners(value={MethodInterceptor.class,InvokedMethodListener.class})
public class Test
{
@org.testng.annotations.Test
public void first()
{
System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName());
}
@org.testng.annotations.Test
public void second()
{
System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName());
}
}
这篇关于TestNG中的IInvokedMethodListener和IMethodInterceptor有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!