如何根據條件停用 TestNG 測試?
TestNG 支援多種方法來跳過或忽略 @Test 執行。根據需求,使用者可以完全跳過測試而不執行它,或者根據特定條件跳過測試。如果在執行時滿足條件,則跳過測試中剩餘的程式碼。
以下是跳過 @Test 執行的方法:
在 @Test 中使用引數 enabled=false。預設情況下,此引數設定為 True。
使用 throw new SkipException(String message) 跳過測試。
條件跳過 – 使用者可以進行條件檢查。如果滿足條件,它將丟擲 SkipException 並跳過其餘程式碼。
在本文中,我們將說明如何進行條件跳過。
解決此問題的方法/演算法:
步驟 1 - 建立一個名為 NewTestngClass 的 TestNG 類。
步驟 2 - 在類中編寫兩個不同的 @Test 方法,如程式程式碼所示。
第 1 個 @Test 方法 - 它設定為 enabled=true。它將執行,TestNG 將列印輸出。
第 2 個 @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() public void testcase1(){ System.out.println("Testcase 1 - executed"); } @Test public void testcase2(){ boolean DataAvailable=false; System.out.println("Test Case2 - 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 1 - executed Test Case2 - Conditional Skip Test ignored. =============================================== Default Suite Total tests run: 2, Passes: 1, Failures: 0, Skips: 1 ===============================================