如何在 TestNG 中按顺序执行所有方法?

testngrest assureddynamic programming更新于 2025/5/6 5:07:17

TestNG 类可以有不同的测试,如 test1、test2、test3 等。一旦用户运行由各种测试组成的 TestNG 类,它会根据提供的名称按字母顺序运行测试用例。但是,用户可以为这些测试分配优先级,以便这些测试可以按照用户的优先级运行。优先级从 0 开始,按递增顺序排列。优先级 0 具有最高优先级,优先级增加时优先级会降低,如 1、2、3 等。

在本文中,让我们分析一下不同情况下执行顺序的发生方式。

场景 1

如果 test2 (priority=0)、test1(priority=1)、test3(priority=2),则 test2 将首先运行,然后是 test1,依此类推,具体取决于优先级。

解决此问题的方法/算法

  • 步骤 1:为 TestNG 导入 o​​rg.testng.annotations.Test。

  • 步骤 2:将注释写为 @test

  • 步骤 3:为 @test 注释创建一个方法,作为 test1,并提供优先级 = 1。

  • 步骤 4:重复上述步骤test2 和 test3 的优先级分别为 0 和 2。

  • 步骤 5:现在创建 testNG.xml。

  • 步骤 6:现在,运行 testNG.xml 或直接在 IDE 中运行 testNG 类,或使用命令行编译并运行它。

示例

以下代码创建 TestNG 类并显示执行的优先级顺序:

import org.testng.annotations.Test;
public class OrderofTestExecutionInTestNG {
    @Test(priority=1)
    public void test1() {
        System.out.println("Starting execution of TEST1");
    }
    @Test(priority=0)
    public void test2() {
        System.out.println("Starting execution of TEST2");
    }
    @Test(priority=2)
    public void test3() {
        System.out.println("Starting execution of TEST3");
    }

输出

Starting execution of TEST2
Starting execution of TEST1
Starting execution of TEST3

场景 2

如果 test2 (priority=0)、test1(priority=1) 且 test3 没有优先级,则 test2 将首先运行,然后是 test3,最后是 test1。由于 test3 没有用户定义的优先级,TestNG 将其指定为优先级 = 0,并且按字母顺序 test2 排在第一位,然后是 test3。

解决此问题的方法/算法

  • 步骤 1:为 TestNG 导入 o​​rg.testng.annotations.Test。

  • 步骤 2:将注释编写为 @test

  • 步骤 3:为 test1 的 @test 注释创建一个方法并提供优先级 = 1。

  • 步骤 4:对优先级为 0 的 test2 和 test 3 重复上述步骤,并且分别不提供任何优先级。

  • 步骤 5:现在创建 testNG.xml

  • 步骤 6:现在,运行 testNG.xml 或直接在 IDE 中运行 testNG 类,或使用命令行编译并运行它。

示例

以下代码创建 TestNG 类并显示执行的优先顺序:

import org.testng.annotations.Test;
public class OrderofTestExecutionInTestNG {
    @Test(priority=1)
    public void test1() {
        System.out.println("Starting execution of TEST1");
    }
    @Test(priority=0)
    public void test2() {
        System.out.println("Starting execution of TEST2");
    }
    @Test()
    public void test3() {
        System.out.println("Starting execution of TEST3");
    }

输出

Starting execution of TEST2
Starting execution of TEST3
Starting execution of TEST1


相关文章