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

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

一个TestNG类可以有不同的测试,比如test1,test2,test3等。一旦用户运行包含多个测试的TestNG类,根据提供的名称,它按字母顺序运行测试用例。然而,用户可以给这些测试分配优先级,以便按照用户的优先级运行这些测试。优先级从0开始,按递增顺序排列。优先级0具有最高优先级,当优先级增加时,优先级减小为1、2、3等。

在本文中,让我们分析执行顺序如何以不同的方式进行。

场景1

如果test2(优先级=0),test1(优先级=1),test3(优先级=2),那么test2将首先运行,然后是test1,根据优先级依次进行。

步骤

  • 步骤1: 导入org.testng.annotations.Test来使用TestNG。

  • 步骤2: 写入注释@test。

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

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

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

  • 步骤6: 现在,通过IDE运行testNG.xml或直接运行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(优先级=0),test1(优先级=1)和test3没有优先级,则test2将首先运行,之后是test3,最后是test1。由于test3没有用户定义的优先级,TestNG将其分配为优先级=0,按字母顺序先运行test2,然后运行test3。

步骤

  • 步骤1:导入org.testng.annotations.Test进行TestNG测试。

  • 步骤2:写一个注释 @test。

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

  • 步骤4:重复步骤2和步骤3,分别对test2和test3提供优先级0,不提供任何优先级。

  • 步骤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

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程