如何在 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+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.