如果 TestNG 中的条件满足,如何通过 BeforeSuite 注释强制结束整个测试套件?

testngrest assureddynamic programming更新于 2025/6/2 8:52:17

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

条件跳过 是强制结束整个测试套件的正确方法,如果在 @BeforeSuite 方法中条件满足。

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

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

解决此问题的方法/算法:

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

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

    第一和第二个 @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.

相关文章