在 TestNG 中跳过测试的最佳实践是什么?
TestNG 支持多种方法来跳过或忽略 @Test 的执行。根据需求,用户可以完全跳过测试而不执行它,或者根据特定条件跳过测试。如果在执行时满足条件,则跳过测试中剩余的代码。
以下是在 @Test 执行中跳过测试的方法:
在 @Test 中使用参数 enabled=false。默认情况下,此参数设置为 true。
使用 throw new SkipException(String message) 跳过测试。
条件跳过 - 用户可以进行条件检查,如果满足条件,则会抛出 SkipException 并跳过其余代码。
但是,当我们谈论跳过测试用例的最佳实践时,它取决于多个因素,例如功能是否不可用、测试是否存在错误或此测试是否依赖于进一步执行。
在本文中,我们将说明当存在对跳过测试的依赖关系时,在类中跳过测试的最佳实践是什么。
解决此问题的方法/算法
步骤 1:创建一个 TestNG 类 - NewTestngClass。
步骤 2:在类 NewTestngClass 中编写 3 个不同的 @Test 方法,如编程代码部分所示。
第 1 个 @Test 方法
它将像简单方法一样执行。
第 2 个 @Test 方法
它抛出 SkipException。TestNG 将打印代码的第一行,并在到达 SkipExecution 代码后立即跳过。有一个静态方法实际上跳过了测试,并且相同的静态方法在 @Test 中被调用,以便可以轻松地忽略它,并且不需要进一步的更改。
第 3 个 @Test 方法
它依赖于第 2 个 @test 方法。
步骤 3:现在创建如下所示的 testNG.xml 来运行 TestNG 类。
步骤 4:现在,运行 testNG.xml 或直接在 IDE 中运行 TestNG 类,或者使用命令行编译并运行它。
示例
以下代码用于常见的 TestNG 类 - NewTestngClass
src/ NewTestngClass.java
import org.testng.SkipException;
import org.testng.annotations.Test;
public class NewTestngClass {
@Test()
public void testcase1(){
System.out.println("Testcase 1 - executed");
}
@Test
public void testcase2(){
System.out.println("Testcase 2 - skip exception example");
skipTest("BUG-1000-Functionality is Broken");
System.out.println("Testcase 2 - Do Not execute");
}
@Test(dependsOnMethods = { "testcase2" })
public void testcase3(){
System.out.println("Test Case3 - Conditional Skip");
}
public static void skipTest(String reason) {
throw new SkipException("Test voluntarily skipped. Reason: " + reason);
}
}
testng.xml
这是一个配置文件,用于组织和运行 TestNG 测试用例。
当只需要执行有限的测试而不是完整的套件时,它非常方便。
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name = "Suite1">
<test name = "test1">
<classes>
<class name = "NewTestngClass"/>
</classes>
</test>
</suite>
输出
Testcase 2 - skip exception example Test ignored. Testcase 1 - executed Test ignored. =============================================== suite Total tests run: 3, Passes: 1, Failures: 0, Skips: 2 ===============================================
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP