如何在 TestNG 的 teardown 方法中獲取已執行測試方法的名稱?


TestNG 支援原生依賴注入。它允許在方法中宣告額外的引數。在執行時,TestNG 會自動用正確的值填充這些引數。以下是一組 TestNG 中的原生依賴項

  • ITestContext
  • XmlTest
  • Method
  • ITestResult

這些依賴項有助於檢索測試方法的名稱。可以在測試執行之前或之後檢索測試方法的名稱。

  • 如果使用者希望在測試方法執行之前獲取其名稱,則可以使用 **@BeforeMethod** 來檢索它。

  • 另一方面,如果使用者想知道剛剛執行了哪個測試方法,則可以使用 **@AfterMethod**。可以在這些方法中的任何一箇中編寫實際程式碼來檢索測試方法的名稱。

**@BeforeMethod** 和 **@AfterMethod** 都支援所有這些原生依賴項。以下是這些依賴項的完整訪問許可權:

註解ITestContextXmlTestMethodITestResult
BeforeSuite
BeforeTest
BeforeGroups
BeforeClass
BeforeMethod
Test
AfterMethod
AfterClass
AfterGroups
AfterTest
AfterSuite

在這篇文章中,我們將使用 Method 依賴項來演示如何檢索測試方法的名稱。但是,任何這些依賴項都可以用於 **@BeforeMethod** 或 **@AfterMethod**。唯一的區別在於 **import** 部分,其中應根據使用的原生依賴項匯入相應的庫。

假設使用者希望在測試方法執行後檢索其名稱。在這種情況下,程式碼將寫入 **@AfterMethod** 中以檢索測試方法的名稱。由於 **@AfterMethod** 在每次 **@Test** 方法執行後都會執行,因此測試方法的名稱將在其執行後列印。

解決此問題的方法/演算法

  • **步驟 1** - 建立一個 TestNG 類 **NewTestngClass** 並編寫 **@AfterMethod 方法**。

  • **步驟 2** - 在 **@AfterMethod** 中編寫以下程式碼

public void tearDown(Method method) {
   System.out.println("Test name: " + method.getName());
}

**注意** - 可以使用其餘三個原生依賴項中的任何一個來代替引數 Method。例如,**ITestContext** 或 **XmlTest** 或 **ITestResult**。

  • **步驟 3** - 在 **NewTestngClass** 類中編寫兩個不同的 **@Test** 方法。

  • **步驟 4** - 建立如下所示的 **testNG.xml** 來執行 TestNG 類。

  • **步驟 5** - 最後,執行 **testNG.xml** 或直接在 IDE 中執行 TestNG 類,或者使用命令列編譯並執行它。

示例

對通用的 TestNG 類 **NewTestngClass** 使用以下程式碼:

src/ NewTestngClass.java

import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
import java.lang.reflect.Method;
public class NewTestngClass {
   @Test
   public void testCase1() {
      System.out.println("in test case 1 of NewTestngClass");
   }
   @Test
   public void testCase2() {
      System.out.println("in test case 2 of NewTestngClass");
   }
   @AfterMethod
   public void tearDown(Method method) {
      System.out.println("Test name: " + method.getName());
   }
}

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>

輸出

in test case 1 of NewTestngClass
Test name: testCase1
in test case 2 of NewTestngClass
Test name: testCase2
===============================================
Suite1
Total tests run: 2, Passes: 2, Failures: 0, Skips: 0
===============================================

更新於: 2022年1月12日

3K+ 瀏覽量

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告