After a tedious work of framing testcases in TestNG class based on priority, if a situation arise to add a test case in between any of those test methods, it will lead you to an annoyed situation of incrementing priorities of all the test methods below the newly inserted test case. I had faced such a situation. Not understood? don't worry, I will give you a sample code to make you understand where I was halted.
Here I am giving the listener code which you have to include in your project.
Here I wanted to add a test method after register account. After inserting the test method, I was required to increment priority of all the following test methods. In my case there were many methods required to be incremented which is not an easy task. So I searched for a solution and finally found the annotation transformer listener which helped me.import org.testng.annotations.Test; public class testNGPriorityExample { @Test
(priority=1)
public void registerAccount() { System.out.println("First register your account"); } @Test(priority=2) public void sendEmail() { System.out.println("Send email after login"); } @Test(priority=3) public void login() { System.out.println("Login to the account after registration"); } }
Here I am giving the listener code which you have to include in your project.
package testpackage;Below is the testng.xml format required.
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import org.testng.IAnnotationTransformer;
import org.testng.annotations.ITestAnnotation;
public class PriorityAnnotationTransformer implements IAnnotationTransformer
{
static ClassPool s_ClassPool = ClassPool.getDefault();
@Override
public void transform(ITestAnnotation p_annotation, Class p_testClass, Constructor p_testConstructor, Method p_testMethod)
{
p_annotation.setPriority(getMethodLineNumber(p_testMethod));
}
private int getMethodLineNumber(Method p_testMethod)
{
try
{
CtClass cc = s_ClassPool.get(p_testMethod.getDeclaringClass().getCanonicalName());
CtMethod methodX = cc.getDeclaredMethod(p_testMethod.getName());
return methodX.getMethodInfo().getLineNumber(0);
}
catch(Exception e)
{
throw new RuntimeException("Getting of line number of method "+p_testMethod+" failed", e);
}
}
}
<?xml version="1.0" encoding="UTF-8"?>
<suite name="Customer" parallel="false">
<listeners>
<listener class-name="testpackage.Transformer"/>
</listeners>
<test name="Test1">
<classes>
<class name="testpackage.Testclass"/>
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->