在TestNG中,IInvokedMethodListener和IMethodInterceptor有什么区别?

4

在Java中,拦截器和监听器有什么基本区别?如果我同时添加两者,哪一个会先被调用?

1个回答

4

1) IMethodInterceptor允许用户修改要执行的方法(或测试)列表。 2) IInvokedMethodListener允许用户在方法执行前/后执行某些操作。例如清理或设置。 3) 首先调用IMethodInterceptor,以便如果用户希望修改要执行的方法列表,则用户可以更改它并将其传递给TestRunner。 请参见下面的示例代码:

    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());
    }
}

如果我在一个类中实现了两个接口,第一次运行会被拦截器拦截吗? - Ram Prasath

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接