testng中如何让一个class的method按优先级全部运行完

本文详细解析了TestNG框架的运行机制,特别是在处理测试类和方法优先级时的内部逻辑。通过引入RePrioritizingListener监听器,实现了按类优先运行所有方法的功能,避免了跨类方法的交错执行,确保了测试流程的清晰和有序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

abcnull

您的打赏是我创作的动力之一

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值