26
Mar

Executing all tests of priority = 1 with TestNG

TestNG allows to execute a specific priority function by means of custom implementation of “IMethodInterceptor” interface. Steps involved are:

Step 1: Custom implementation of intercept method of IMethodInterceptor interface:
———————————————————————————–

public interface IMethodInterceptor {
List intercept(List methods, ITestContext context);
}

eg. following custom implementation returns a list of all methods with priority 1

import java.util.ArrayList;
import java.util.List;
import org.testng.IMethodInstance;
import org.testng.IMethodInterceptor;
import org.testng.ITestContext;
import org.testng.annotations.Test;

public class PriorityInterceptor implements IMethodInterceptor {

@Override
public List intercept(List methods, ITestContext context) {
List result = new ArrayList();
for (IMethodInstance method : methods) {
Test testMethod = method.getMethod().getConstructorOrMethod().getMethod().getAnnotation(Test.class);
if (testMethod.priority() == 1) {
result.add(method);
}
}
return result;
}
}

Step 2: Your TestNG methods:
—————————-

import org.testng.annotations.BeforeClass;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;

@Listeners(PriorityInterceptor.class)
public class TestA {

@Test(priority=1)
public void myFunction(){
System.out.println(“Priority 1”);
}

@Test(priority=2)
public void myFunction2(){
System.out.println(“Priority 2”);
}
}

OUTPUT:
——-
only Priority 1 test is executed