一个 TestNG 类可以有不同的测试,如test1、test2、test3等。一旦用户运行由各种测试组成的 TestNG 类,它就会根据提供的名称按字母顺序运行测试用例。但是,用户可以为这些测试分配优先级,以便这些测试可以按照用户的优先级运行。优先级从“ 0 ”开始,具有最高优先级,随着数字的增加,优先级降低。
在这篇文章中,我们来分析一下TestNG中优先执行的顺序是如何工作的。
方案 1
如果test2 (priority=0), test1 (priority=1), test3 (priority=2),则test2将首先运行,然后test1以此类推。
解决此问题的方法/算法 -
第 1 步- 为 TestNG 导入 org.testng.annotations.Test。
第 2 步- 将注释写为@test
第 3 步- 为@test注释创建一个方法,作为test1优先级=1。
步骤 4 -分别以优先级“0”和“2”重复test2和test3的步骤。
第 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 分配它的 priority=0 并且按字母顺序,test2先出现,然后是test3。
解决此问题的方法/算法 -
第 1 步- 为 TestNG 导入 org.testng.annotations.Test。
第 2 步- 将注释写为@test
第 3 步- 为@test注释创建一个方法作为test1,优先级 = 1。
第 4 步- 重复test2和test 3的步骤以获取优先级 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