如何在 TestNG 中斷言失敗後繼續執行測試?
一個 TestNG 類可以包含不同的測試,例如 test1、test2、test3 等。在執行測試套件時可能會出現一些失敗,使用者可能會在 @Test 方法之間遇到失敗。一旦某個測試方法失敗,他希望繼續執行,以便能夠及時發現所有失敗。預設情況下,如果在 @Test 方法中發生故障,TestNG 會退出該 @Test 方法並從下一個 @Test 方法繼續執行。
這裡,用例是在同一個 @Test 方法中即使斷言失敗也要繼續執行下一行。
有多種方法可以解決此類用例
使用 SoftAssert 類使用軟斷言。即使斷言失敗,它也會繼續執行,並且可以使用 assertAll() 函式在最後捕獲所有失敗。
使用驗證而不是斷言。基本上,所有斷言都將更改為驗證。請注意,TestNG 不支援驗證。使用者應該使用 try-catch 塊編寫自己的自定義方法來處理斷言並繼續執行。
使用 try catch 塊。這更像是一種故障安全技術,而不是在斷言失敗後準確執行程式碼的下一行。
在本文中,讓我們說明如何在 TestNG 中使用 SoftAssert 在斷言失敗時繼續執行。
解決此問題的方法/演算法
步驟 1:匯入 org.testng.annotations.Test 用於 TestNG。
步驟 2:在 NewTest 類中編寫一個註釋作為 @test
步驟 3:為 @Test 註釋建立一個方法,例如 testCase1。
步驟 4:如程式部分所示,使用 SoftAssert 類新增多個斷言。
步驟 5:重複 testCase2 的步驟。使用 assert 新增斷言。
步驟 6:現在建立 testNG.xml。
步驟 7:現在,執行 testNG.xml 或直接在 IDE 中執行 TestNG 類,或者使用命令列編譯並執行它。
示例
以下程式碼用於建立一個 TestNG 類並顯示 Listener 功能
src/NewTest.java
import org.testng.Assert; import org.testng.annotations.Test; import org.testng.asserts.SoftAssert; public class NewTest { private SoftAssert softAssert = new SoftAssert(); @Test(priority = 0) public void testCase1() { System.out.println("in test case 1 of NewTest"); softAssert.assertTrue(false); softAssert.assertNotEquals(5,6); softAssert.assertEquals(1, 2); softAssert.assertAll(); } @Test(priority = 1) public void testCase2() { System.out.println("in test case 2 of NewTest"); Assert.assertTrue(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"> <test name="test"> <classes> <class name="NewTest" /> </classes> </test> </suite>
輸出
[INFO] Running TestSuite in test case 1 of NewTestngClass in test case 2 of NewTestngClass [ERROR] Tests run: 2, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0.832 s <<< FAILURE! - in TestSuite [ERROR] NewTest.testCase1 Time elapsed: 0.016 s <<< FAILURE! java.lang.AssertionError: The following asserts failed: expected [true] but found [false], expected [2] but found [1] at NewTest.testCase1(newTest.java:15) [INFO] [INFO] Results: [INFO] [ERROR] Failures: [ERROR] NewTest.testCase1:15 The following asserts failed: expected [true] but found [false], expected [2] but found [1] [INFO] [ERROR] Tests run: 2, Failures: 1, Errors: 0, Skipped: 0