如何在 TestNG 失敗時新增自定義訊息?
TestNG 支援許多**斷言**。它擁有**org.testng.Assert** 類,該類擴充套件了 Java 物件類**java.lang.object**。每當發生失敗時,使用者都希望獲得自定義的失敗訊息,以便輕鬆進行根本原因分析。TestNG 支援帶有自定義失敗訊息的斷言。但是,訊息完全是可選的。
**語法**如下:
Assert.<assertMethod>(expected, actual, message)
如果使用者沒有提供訊息,TestNG 會列印預設錯誤訊息;但如果使用者設定了訊息,則 TestNG 會丟擲錯誤以及使用者設定的自定義訊息。
在本文中,我們將瞭解如何在 TestNG 失敗時設定自定義訊息。
解決此問題的方法/演算法
**步驟 1** - 建立一個 TestNG 類,**NewTestngClass**。
**步驟 2** - 在類中編寫三個不同的**@Test** 方法,以便在三個不同的斷言中失敗,如下面的程式設計程式碼部分所示。
**步驟 3** - 建立如下所示的**testNG.xml** 以執行 TestNG 類。
**步驟 4** - 最後,執行**testNG.xml** 或直接在 IDE 中執行 TestNG 類,或者使用命令列進行編譯和執行。
示例
使用以下程式碼作為通用 TestNG 類,**NewTestngClass** -
src/ NewTestngClass.java
import org.testng.Assert; import org.testng.annotations.*; public class NewTestngClass { @Test public void test1() { System.out.println("Running test1"); int Id = 1; int newId = 2 ; Assert.assertEquals(Id, newId,"Assert equals validation between id and newId"); } @Test public void test2() { System.out.println("Running test2"); String Id = null; Assert.assertNotNull(Id, "Assert not null validation for Id is failed. Id is null"); } @Test public void test3() { System.out.println("Running test3"); Boolean Id = false; Assert.assertTrue(Id,"Assert True validation failed as Id is not set to true"); } }
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>
輸出
Running test1 java.lang.AssertionError: Assert equals validation between id and newId expected [2] but found [1] Expected :2 Actual :1 ......... Running test2 java.lang.AssertionError: Assert not null validation for Id is failed. Id is null expected object to not be null ............ Running test3 java.lang.AssertionError: Assert True validation failed as Id is not set to true expected [true] but found [false] Expected :true Actual :false ...........
廣告