如何阻止 TestNG 在測試失敗後繼續執行?
一個 TestNG 類可以包含不同的測試,例如 test1、test2、test3 等。在執行測試套件時可能會出現一些失敗,使用者可能會在 @Test 方法之間遇到失敗。一旦測試方法失敗,它就會跳過 @Test 方法的其餘程式碼,並轉到下一個 @Test 方法。但是,使用者可能希望在第一次失敗後跳過所有剩餘的 @Test 方法。
對於此類用例,有兩種最流行的解決方案
編寫 dependsOnMethods 註解 - 但此解決方案僅在使用者知道確切的依賴方法時才有效,否則在大規模套件中將會非常麻煩。
使用 IInvokedMethodListener 在套件中新增通用邏輯。
在本文中,讓我們分析如何使用 IInvokedMethodListener 在第一次失敗後停止站點執行。
解決此問題的方法/演算法
步驟 1:為 TestNG 匯入 org.testng.annotations.Test。
步驟 2:在新 Test 類中編寫一個 @test 註解。
步驟 3:為 @Test 註解建立一個名為 test1 的方法。
步驟 4:對 test2 和 test3 重複這些步驟。在 test2 中新增失敗斷言。
步驟 5:現在,建立一個使用 IInvokedMethodListener 檢查先前 @Test 方法狀態的 ListenerClass。如果它獲得失敗狀態,則忽略剩餘的套件。
步驟 6:現在建立 testNG.xml 並新增 Listener 類。
步驟 7:現在,執行 testNG.xml 或直接在 IDE 中執行 TestNG 類,或者使用命令列編譯並執行它。
示例
以下程式碼用於建立一個 TestNG 類並顯示 Listener 功能
src/NewTest.java
import org.testng.annotations.Test; public class NewTest { @Test() public void testCase1() { System.out.println("in test case 1 of NewTest"); } @Test() public void testCase2() { System.out.println("in test case 2 of NewTest"); assert false; } @Test() public void testCase3() { System.out.println("in test case 3 of NewTest"); } }
src/ListenerClass.java
import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.ITestResult; import org.testng.SkipException; public class ListenerClass implements IInvokedMethodListener { private boolean hasFailures = false; @Override public void beforeInvocation(IInvokedMethod method, ITestResult testResult) { synchronized (this) { if (hasFailures) { throw new SkipException("Skipping this test"); } } } @Override public void afterInvocation(IInvokedMethod method, ITestResult testResult) { if (method.isTestMethod() && !testResult.isSuccess()) { synchronized (this) { hasFailures = true; } } } }
testng.xml
這是一個用於組織和執行 TestNG 測試用例的配置檔案。
當只需要執行有限的測試而不是完整的套件時,它非常方便。
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd"> <suite name="Parent_Suite"> <listeners> <listener class-name="ListenerClass"/> </listeners> <test name="group test"> <classes> <class name="NewTest" /> </classes> </test> </suite>
輸出
[INFO] Running TestSuite in test case 1 of NewTest in test case 2 of NewTest [ERROR] Tests run: 3, Failures: 1, Errors: 0, Skipped: 1, Time elapsed: 0.671 s <<< FAILURE! - in TestSuite [ERROR] NewTest.testCase2 Time elapsed: 0.009 s <<< FAILURE! java.lang.AssertionError at NewTest.testCase2(newTest.java:14) [INFO] [INFO] Results: [INFO] [ERROR] Failures: [ERROR] NewTest.testCase2:14 [INFO] [ERROR] Tests run: 3, Failures: 1, Errors: 0, Skipped: 1