Whats the differences between IInvokedMethodListener and IMethodInterceptor in TestNG?

非 Y 不嫁゛ 提交于 2019-12-12 12:25:46

问题


Whats the basic difference between Interceptor and Listener in java? If i add both, which will be invoked first?


回答1:


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


来源:https://stackoverflow.com/questions/28824620/whats-the-differences-between-iinvokedmethodlistener-and-imethodinterceptor-in-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!