如何在运行时跳过 TestNG 测试?
TestNG 支持多种跳过或忽略 @Test 执行的方法。根据需求,用户可以跳过整个测试而不执行,或者根据特定条件跳过测试。如果执行时条件满足,则跳过测试中的剩余代码。
可以使用以下方法跳过 @Test 执行 −
在 @Test 中使用参数 enabled=false。默认情况下,此参数设置为 True。
使用 throw new SkipException(String message) 跳过测试。
有条件跳过 − 用户可以进行条件检查。如果满足条件,它将抛出 SkipException 并跳过剩余代码。
在本文中,我们将说明如何使用上述三种方法跳过类中的测试。
解决此问题的方法/算法
步骤 1 − 创建一个 TestNG 类,NewTestngClass
步骤 2 − 在类 NewTestngClass 中编写三个不同的 @Test 方法,如编程代码部分所示。
第一个 @Test 方法 的值为 enabled=false。它根本不会执行,TestNG 会在运行时完全忽略它。即使在合并的运行详情中,它也不会考虑这一点,因此只会执行两个测试。
第二个 @Test 方法 抛出 SkipException。TestNG 将打印第一行代码,并在到达 SkipExecution 代码时立即跳过其余部分。
第三个 @Test 方法
这是有条件跳过的。代码检查 DataAvailable 参数是 True 还是 False。如果为 False,则会抛出 SkipException 并跳过测试。但是,如果 DataAvailable 为 True,则不会抛出 SkipException 并继续执行。步骤 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(enabled=false) public void testcase1(){ System.out.println("Testcase 1 - Not executed"); } @Test public void testcase2(){ System.out.println("Testcase 2 - skip exception example"); throw new SkipException("Skipping this exception"); } @Test public void testcase3(){ boolean DataAvailable=false; System.out.println("Test Case3 - Conditional Skip"); if(!DataAvailable) throw new SkipException("Skipping this exception"); System.out.println("Executed Successfully"); } }
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. Test Case3 - Conditional Skip Test ignored. =============================================== Suite1 Total tests run: 2, Passes: 0, Failures: 0, Skips: 2 ===============================================