如何在執行時跳過 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 ===============================================