在 TestNG 中跳過測試的最佳實踐是什麼?
TestNG 支援多種方法來跳過或忽略 @Test 的執行。根據需求,使用者可以完全跳過測試而不執行它,或者根據特定條件跳過測試。如果在執行時滿足條件,則跳過測試中剩餘的程式碼。
以下是在 @Test 執行中跳過測試的方法:
在 @Test 中使用引數 enabled=false。預設情況下,此引數設定為 true。
使用 throw new SkipException(String message) 跳過測試。
條件跳過 - 使用者可以進行條件檢查,如果滿足條件,則會丟擲 SkipException 並跳過其餘程式碼。
但是,當我們談論跳過測試用例的最佳實踐時,它取決於多個因素,例如功能是否不可用、測試是否存在錯誤或此測試是否依賴於進一步執行。
在本文中,我們將說明當存在對跳過測試的依賴關係時,在類中跳過測試的最佳實踐是什麼。
解決此問題的方法/演算法
步驟 1:建立一個 TestNG 類 - NewTestngClass。
步驟 2:在類 NewTestngClass 中編寫 3 個不同的 @Test 方法,如程式設計程式碼部分所示。
第 1 個 @Test 方法
它將像簡單方法一樣執行。
第 2 個 @Test 方法
它丟擲 SkipException。TestNG 將列印程式碼的第一行,並在到達 SkipExecution 程式碼後立即跳過。有一個靜態方法實際上跳過了測試,並且相同的靜態方法在 @Test 中被呼叫,以便可以輕鬆地忽略它,並且不需要進一步的更改。
第 3 個 @Test 方法
它依賴於第 2 個 @test 方法。
步驟 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(){ System.out.println("Testcase 2 - skip exception example"); skipTest("BUG-1000-Functionality is Broken"); System.out.println("Testcase 2 - Do Not execute"); } @Test(dependsOnMethods = { "testcase2" }) public void testcase3(){ System.out.println("Test Case3 - Conditional Skip"); } public static void skipTest(String reason) { throw new SkipException("Test voluntarily skipped. Reason: " + reason); } }
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. Testcase 1 - executed Test ignored. =============================================== suite Total tests run: 3, Passes: 1, Failures: 0, Skips: 2 ===============================================