如何在 TestNG 中獲取方法執行時間?


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

  • ITestContext
  • XmlTest
  • Method
  • ITestResult

這些依賴項有助於檢索測試方法執行所花費的時間。只有在測試執行後才能檢索測試方法的執行時間。

如果使用者希望在方法執行後獲取方法執行時間,則可以使用 @AfterMethod 來檢索它。@AfterMethod 支援所有這些原生依賴項。下面提供了這些依賴項的完全訪問許可權:

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

在這篇文章中,我們將使用 ITestResult 依賴項來展示如何檢索每個測試方法的執行時間。

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

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

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

public void name(ITestResult result) {
   System.out.println("in aftermethod of NewTestngClass");
   long a = result.getEndMillis()-result.getStartMillis();
   System.out.println("Time taken to run test is :"+a+" miliiseconds");
}
  • 步驟 3 - 在類 NewTestngClass 中編寫兩個不同的 @Test 方法。

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

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

示例

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

src/ NewTestngClass.java

import org.testng.ITestResult;
import org.testng.annotations.*;
public class NewTestngClass {
   // test case 1
   @Test()
   public void testCase1() throws InterruptedException {
      Thread.sleep(5000);
      System.out.println("in test case 1 of NewTestngClass");
   }
   // test case 2
   @Test()
   public void testCase2() throws InterruptedException {
      Thread.sleep(1000);
      System.out.println("in test case 2 of NewTestngClass");
   }
   @AfterMethod
   public void name(ITestResult result) {
      System.out.println("in aftermethod of NewTestngClass");
      long a = result.getEndMillis()-result.getStartMillis();
      System.out.println("Time taken to run test is :"+a+" miliiseconds");
   }
}

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
in aftermethod of NewTestngClass
Time taken to run test is :5011 miliiseconds
in test case 2 of NewTestngClass
in aftermethod of NewTestngClass
Time taken to run test is :1008 miliiseconds
===============================================
Suite1
Total tests run: 2, Passes: 2, Failures: 0, Skips: 0
===============================================

更新於:2022年1月12日

1K+ 次瀏覽

啟動您的 職業生涯

透過完成課程獲得認證

開始
廣告