测试积点老人 发表于 2019-8-27 11:43:34

testng 中的 method 乱序问题解决

1、问题说明:
出现问题:

2、解决问题方法
(1)顺序控制方法:目前使用了dependsOnMethods和testng.xml中methods中的include方法顺序控制
结果:偶尔方法执行顺序混乱,大概20%的概率
(2)增加顺序控制方法:priority
结果:无效
(3)增加RePrioritizingListener
结果:有效,暂时没有发现乱序问题

详细解决方法如下:
package tools.testng_Listeners;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.HashMap;
import org.testng.IAnnotationTransformer;
import org.testng.Reporter;
import org.testng.annotations.ITestAnnotation;

//Listener to fix TestNG Interleaving issue.I had to re-write this as the original example I had did not allow for priority to be manually set on a test level.
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;

    @Override
    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);

    }

}
然后在testng.xml中添加listener,解决了method乱序问题,目前未发现乱序问题
<listeners>
      <listener class-name="tools.testng_Listeners.RePrioritizingListener"></listener>
    </listeners>

jingzizx 发表于 2019-8-28 10:10:49

:lol,感谢分享

qqq911 发表于 2019-8-28 10:34:42

感谢分享

litingting0214 发表于 2019-8-28 11:42:46

非常感激:P

你好浮戈 发表于 2019-8-28 13:49:17

谢谢分享,感激~
页: [1]
查看完整版本: testng 中的 method 乱序问题解决