testng 框架的运行机理是运行到<test>
中的<classes>
标签中,会把所有<class>
中的<method>
加载到容器中,或者说是把<test>
中所有@Test
注解的方法加载到容器,不管这个 method 或者说这个@Test
注解的方法属于哪一个类,然后全部按照优先级来排序运行,同优先级的比较方法名按照 ascall 编码排序。这样可能导致<classes>
中第一个 class 跑了一个,又去跑第二个 class 的 method,所以可在 testng.xml 文件中添加一个监听器 RePrioritizingListener,主要作用是一个 class 中的 method 可以全部运行完再运行下一个 class
testng.xml 通过如下形式添加:
<listeners>
<listener class-name="com.test.listener.RePrioritizingListener"/>
</listeners>
RePrioritizingListener 写法如下:
public class RePrioritizingListener implements IAnnotationTransformer {
HashMap<Object, Integer> priorityMap = new HashMap<Object, Integer>();
Integer class_priorityCounter = 10000;
// The length of the final priority assigned to each method.
Integer max_testpriorityLength = 4;
public void transform(ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) {
// class of the test method.
Class<?> declaringClass = testMethod.getDeclaringClass();
// Current priority of the test assigned at the test method.
Integer test_priority = annotation.getPriority();
// Current class priority.
Integer current_ClassPriority = priorityMap.get(declaringClass);
if (current_ClassPriority == null) {
current_ClassPriority = class_priorityCounter++;
priorityMap.put(declaringClass, current_ClassPriority);
}
String concatenatedPriority = test_priority.toString();
// Adds 0's to start of this number.
while (concatenatedPriority.length() < max_testpriorityLength) {
concatenatedPriority = "0" + concatenatedPriority;
}
// Concatenates our class counter to the test level priority (example
// for test with a priority of 1: 1000100001; same test class with a
// priority of 2: 1000100002; next class with a priority of 1. 1000200001)
concatenatedPriority = current_ClassPriority.toString() + concatenatedPriority;
//Sets the new priority to the test method.
annotation.setPriority(Integer.parseInt(concatenatedPriority));
String printText = testMethod.getName() + " Priority = " + concatenatedPriority;
Reporter.log(printText);
System.out.println(printText);
}
}