如何在 TestNG 中满足某个条件时,从 BeforeSuite 注解强制结束整个测试套件?


TestNG 支持多种方法来跳过或忽略 @Test 的执行。根据需求,用户可以在满足某个条件时,从 BeforeSuite 跳过整个测试而根本不执行它。如果在执行时满足条件,它将跳过 @Test 方法的运行。

条件跳过 是一种在 @BeforeSuite 方法中满足某个条件时强制结束整个测试套件的正确方法。

  • 条件跳过 - 用户可以进行条件检查。如果满足条件,它将抛出 SkipException 并跳过其余代码。

在本文中,我们将演示如何根据条件强制结束整个测试套件。

解决此问题的方法/算法

  • 步骤 1 - 创建一个 TestNG 类,NewTestngClass

  • 步骤 2 - 在类中编写两个不同的 @Test 方法和一个 @BeforeSuiteNewTestngClass,如下面的编程代码部分所示。

    第 1 个和第 2 个 @Test 方法 - 它将根据 @BeforeSuite 条件跳过执行。

    @BeforeTest 方法 - 它是条件跳过。代码检查 DataAvailable 参数是 True 还是 False。如果是 False,则抛出 SkipException 并跳过测试。但是,如果 DataAvailable 为 True,则不会抛出 SkipException 并继续执行。确保 SkipException 未在 catchcatch 块中捕获。否则,它将抛出

    SkipException

    并继续执行。


  • 步骤 3 - 创建如下所示的 testNG.xml 以运行 TestNG 类。

  • 步骤 4 - 最后,运行 testNG.xml 或直接在 IDE 中运行 TestNG 类,或者使用命令行编译并运行它。

程序代码

对于常见的 TestNG 类 NewTestngClass,使用以下代码 -

src/ NewTestngClass.java

import org.testng.SkipException; import org.testng.annotations.*; public class NewTestngClass { @Test() public void testcase1(){ System.out.println("Testcase 1 - executed"); } @Test() public void testcase2(){ System.out.println("Testcase 2 - executed"); } @BeforeSuite public void beforesuite(){ boolean DataAvailable=false; System.out.println("BeforeSuite - 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>

输出

BeforeSuite - Conditional Skip
===============================================
Default Suite
Total tests run: 2, Passes: 0, Failures: 0, Skips: 2
Configuration Failures: 0, Skips: 1
===============================================
Process finished with exit code 0
Test ignored.
Test ignored.

更新于: 2022-01-12

1K+ 浏览量

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告