Here's one approach.
First define an annotation that looks like below
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
@Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
@Target({METHOD, TYPE})
public @interface Repeat {
int times() default 1;
}
Now use the annotation in your test class either at the class level or at the method level as below.
import org.testng.ITestResult;
import org.testng.Reporter;
import org.testng.annotations.Test;
@Repeat(times = 10)
public class SampleTestClass {
@Test
public void testMethod1() {
System.err.println("running testMethod1 for iteration # " + invocationCount());
}
@Test
public void testMethod2() {
System.err.println("running testMethod2 for iteration # " + invocationCount());
}
private static int invocationCount() {
ITestResult itr = Reporter.getCurrentTestResult();
return itr.getMethod().getCurrentInvocationCount();
}
}
In order for your tests to be repeatable, now define an annotation transformer that looks like below
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import org.testng.IAnnotationTransformer;
import org.testng.annotations.ITestAnnotation;
public class RepeatableTest implements IAnnotationTransformer {
@Override
public void transform(ITestAnnotation annotation, Class testClass, Constructor testConstructor,
Method testMethod) {
if (testClass != null) {
Repeat repeat = (Repeat) testClass.getAnnotation(Repeat.class);
if (repeat == null) {
//If annotation was not found at class level then return.
return;
}
annotation.setInvocationCount(repeat.times());
return;
}
if (testMethod == null) {
return;
}
Repeat repeat = testMethod.getAnnotation(Repeat.class);
if (repeat == null) {
//If we didnt find the annotation at the method level then search for the annotation
// at the class level to which the method belongs to
repeat = testMethod.getDeclaringClass().getAnnotation(Repeat.class);
if (repeat == null) {
return;
}
}
annotation.setInvocationCount(repeat.times());
}
}
Now finally define your test suite that looks like below.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="my_suite" verbose="2">
<listeners>
<listener class-name="com.rationaleemotions.repeat.RepeatableTest"/>
</listeners>
<test name="my_test" verbose="2">
<classes>
<class name="com.rationaleemotions.repeat.SampleTestClass"/>
</classes>
</test>
</suite>
Thanks & Regards
Krishnan Mahadevan
"All the desirable things in life are either illegal, expensive, fattening or in love with someone else!"
My Scribblings @ http://wakened-cognition.blogspot.com/