White Box Testing
Test your code
   Home      TestNG Method Interceptors
 

TestNG Method Interceptors

Method Interceptors gives you more control on methods execution ordering. Test NG defines below interface, implement interceptor class using this

public interface IMethodInterceptor {

  List<IMethodInstance> intercept(List<IMethodInstance> methods, ITestContext context);

}

 

The list of methods passed in parameters are all the methods that can be run in any order. For example see MyInterceptor

 

package testNGInterceptors;

 

import java.util.ArrayList;

import java.util.List;

 

import org.testng.IMethodInstance;

import org.testng.IMethodInterceptor;

import org.testng.ITestContext;

 

public class MyInterceptor implements IMethodInterceptor {

        

    @Override

    public List<IMethodInstance> intercept(List<IMethodInstance> methods, ITestContext context) {

      

       List<IMethodInstance> newList = new ArrayList<IMethodInstance>(methods.size());

      

       for(IMethodInstance m : methods)

       {

              String MethodName =m.getMethod().getMethodName();

              if (MethodName.contains("Add"))

              {

                     newList.add(0, m);

              }

              else if (MethodName.contains("concurrency"))

              {

                     newList.add(m);

              }

              else if (MethodName.contains("exceptionTest"))

              {

                     newList.add(m);

              }

              else

              {

                     newList.add(m);

              }

       }

                 

        return newList;

    }

}

 

 

To pass methods from a class to test interceptors

@Listeners(testNGInterceptors.MyInterceptor.class)

public class CalculatorTestAdd {

}

 

 

To specify programmatically

TestNG tng = new TestNG();

// set listener

tng.setMethodInterceptor(new MyInterceptor());

 

 

To specify class on commandline

java org.testng.TestNG -listener MyInterceptortestng.xml


Sample Source Code
 
 

 
 
External References