You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TestNG结合DataProvider如何按参数分组顺序执行所有测试方法

问题原因

TestNG 默认按测试方法维度分组执行,会先跑完所有测试类实例的test1方法,再依次跑所有实例的test2、test3方法,这就是你当前执行顺序不符合预期的原因。另外你代码test1方法中this.creds = creds;属于冗余代码,构造方法已经完成了成员变量赋值,不需要重复赋值。你期望输出里的最后一行test3 creds: Creds3属于笔误,实际应为test3 creds: Creds2。

解决方案

你只需要开启 TestNG 的group-by-instances配置,指定按测试类实例分组执行即可,开启后同一个实例的所有测试方法执行完成后,才会执行下一个实例的测试方法,完全符合你的执行顺序要求,同时每个@Test方法独立,Allure 报告也会生成对应的单独测试结果。

方式1:修改 testng.xml 配置

在 suite 标签添加group-by-instances="true"属性即可:

<suite name="测试套件" group-by-instances="true">
    <test name="参数化测试">
        <classes>
            <!-- 替换为你自己的TestTest类全限定名 -->
            <class name="com.example.TestTest"/>
        </classes>
    </test>
</suite>

方式2:Maven 执行场景配置

如果你用 Maven Surefire 插件执行测试,直接在插件配置中添加对应参数即可,不需要改 testng.xml:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>3.2.2</version> <!-- 替换为你实际使用的版本 -->
    <configuration>
        <properties>
            <property>
                <name>group-by-instances</name>
                <value>true</value>
            </property>
        </properties>
    </configuration>
</plugin>

内容的提问来源于stack exchange,提问作者hhrzc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 02:06:04