如何在 TestNG.xml 中保持执行顺序?
在最新版本中,TestNG 按 TestNG.xml 或任何可执行 XML 文件中提到的顺序执行类。但是,有时在旧版本中运行 tesng.xml 时,顺序不会被采纳。TestNG 可能会以随机顺序运行类。在最新版本中,TestNG 按 TestNG.xml 或任何可执行 XML 文件中提到的顺序执行类。但是,有时在旧版本中运行 tesng.xml 时,顺序不会被采纳。TestNG 可能会以随机顺序运行类。
在本文中,我们将讨论如何确保执行顺序按照 tesng.xml 保持不变。
TestNG 支持两个属性 - parallel 和 preserve-order。这些属性用于 testing.xml 中。
Parallel 属性用于并行运行测试。因此,第一个检查是确保执行不是并行发生的以保留执行顺序。Parallel 属性在套件级别提及,因此添加 parallel = "none" 而不是 parallel=""。
Preserver-order 属性在测试级别使用。TestNG 在旧的 jar 中默认将该值设置为 false。这可能导致随机执行。为了确保执行顺序被采纳,我们在 testing.xml 中将该属性设置为 true。
现在,我们将了解如何实现这两个属性以确保执行顺序按照 testing.xml 保持不变。
解决此问题的方法/算法
步骤 1:创建两个 TestNG 类 - OrderofTestExecutionInTestNG 和 NewTestngClass
步骤 2:在每个类(OrderofTestExecutionInTestNG 和 NewTestngClass)中编写两个不同的 @Test 方法。
步骤 3:现在创建 testNG.xml 来运行这两个 TestNG 类,并按如下所示提及 parallel=none 和 preserve-order=true
步骤 4:现在,运行 testNG.xml 或 IDE 中直接运行 TestNG 类,或者使用命令行编译并运行它。
示例
以下代码适用于 TestNG 类 - OrderofTestExecutionInTestNG
import org.testng.annotations.*;
public class OrderofTestExecutionInTestNG {
// test case 1
@Test
public void testCase1() {
System.out.println("in test case 1 of OrderofTestExecutionInTestNG");
}
// test case 2
@Test
public void testCase2() {
System.out.println("in test case 2 of OrderofTestExecutionInTestNG");
}
}
以下代码适用于通用 TestNG 类 - NewTestngClass
import org.testng.annotations.*;
public class NewTestngClass {
@Test
public void testCase1() {
System.out.println("in test case 1 of NewTestngClass");
}
@Test
public void testCase2() {
System.out.println("in test case 2 of NewTestngClass");
}
}
testng.xml
这是一个配置文件,用于组织和运行 TestNG 测试用例。
当只需要执行有限的测试而不是完整套件时,它非常方便。
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name = "Suite1" parallel = "none">
<test name = "test1" preserve-order = "true">
<classes>
<class name = "OrderofTestExecutionInTestNG"/>
<class name = "NewTestngClass"/>
</classes>
</test>
</suite>
输出
in test case 1 of OrderofTestExecutionInTestNG in test case 2 of OrderofTestExecutionInTestNG in test case 1 of NewTestngClass in test case 2 of NewTestngClass =============================================== Suite1 Total tests run: 4, Passes: 4, Failures: 0, Skips: 0 ===============================================
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP