import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
@Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
@Target(value={ElementType.METHOD, ElementType.TYPE})
public @interface Priority {
int value() default 0;
}
package ThreadingTest.Priority;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import org.testng.IMethodInstance;
import org.testng.IMethodInterceptor;
import org.testng.ITestContext;
public class PriorityInterceptor implements IMethodInterceptor {
public List<IMethodInstance> intercept(List<IMethodInstance> methods, ITestContext context) {
Comparator<IMethodInstance> comparator = new Comparator<IMethodInstance>() {
private int getPriority(IMethodInstance mi) {
int result = 0;
Method method = mi.getMethod().getMethod();
Priority a1 = method.getAnnotation(Priority.class);
if (a1 != null) {
result = a1.value();
} else {
Class cls = method.getDeclaringClass();
Priority classPriority = (Priority) cls.getAnnotation(Priority.class);
if (classPriority != null) {
result = classPriority.value();
}
}
return result;
}
public int compare(IMethodInstance m1, IMethodInstance m2) {
return getPriority(m1) - getPriority(m2);
}
};
IMethodInstance[] array = methods.toArray(new IMethodInstance[methods.size()]);
Arrays.sort(array, comparator);
return Arrays.asList(array);
}
}
package ThreadingTest.Priority;
import org.testng.annotations.Test;
public class PriorityTestPlan {
@Test
public void method1() { System.out.println("M1 Default priority");}
@Priority(1)
@Test
public void method2() { System.out.println("M2 Priority 1");}
@Priority(3)
@Test
public void method3() { System.out.println("M3 Priority 3");}
@Priority(-1)
@Test
public void method4() { System.out.println("M4 Priority -1");}
@Priority(2)
@Test
public void method5() { System.out.println("M5 Priority 2");}
@Priority(2)
@Test
public void method6() { System.out.println("M6 Priority 2");}
}
<suite name="PriorityTestSuite" verbose="1" >
<listeners>
<listener class-name="ThreadingTest.Priority.PriorityInterceptor" />
</listeners>
<test name="PriorityTestPlan" preserve-order="true">
<classes>
<class name="ThreadingTest.Priority.PriorityTestPlan"></class>
</classes>
</test>
</suite>
No comments:
Post a Comment