如何在 TestNG 的 @BeforeTest 中設定輸出目錄?


當用戶從 IDE 或命令列執行 **testng.xml** 時,TestNG 支援預設的報告生成。預設情況下,所有報告都生成在 **專案 -> test-output** 資料夾中。如果 **test-output** 資料夾不存在,則 TestNG 會在執行時建立它並儲存所有與結果相關的檔案。

但是,使用者可以提供 TestNG 應該儲存報告的所需位置或資料夾名稱。這可以使用原生依賴注入來完成。它允許在方法中宣告附加引數。在執行時,TestNG 會自動用正確的值填充這些引數。

要在 **@BeforeTest** 中設定輸出目錄,可以使用 **ITestContext** 依賴項。它會在給定路徑建立資料夾,或者如果資料夾已存在則覆蓋它,以儲存最新執行的報告。

在這篇文章中,我們將使用 **ITestContext** 依賴項來說明如何在 TestNG **@BeforeTest** 中設定輸出目錄。

解決這個問題的方法/演算法

  • **步驟 1** - 建立一個 TestNG 類,**NewTestngClass**。

  • **步驟 2** - 在類的 **@BeforeTest** 中編寫以下程式碼:

public void setOutputDirectory(ITestContext context) {
   TestRunner runner = (TestRunner) context;
   String path=System.getProperty("user.dir");
   runner.setOutputDirectory(path+"/output-testng");
}
  • **步驟 3** - 在類 **NewTestngClass** 中編寫一個 **@Test** 方法。

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

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

  • **步驟 6** - 執行完成後,使用者可以檢查專案路徑下是否建立了 **output-testng** 資料夾,並且其中是否包含最新執行的所有報告。在這個例子中,**String path=System.getProperty("user.dir")**; 獲取 TestNG 專案所在的絕對路徑,然後新增資料夾。使用者可以提供任何路徑以在該資料夾中生成報告。

示例

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

src/ NewTestngClass.java

import org.testng.ITestContext;
import org.testng.TestRunner;
import org.testng.annotations.*;
public class NewTestngClass {
   @Test()
   public void testcase1(ITestContext testContext){
      System.out.println("Thread ID: "+Thread.currentThread().getId());
      int currentCount = testContext.getAllTestMethods()[0].getCurrentInvocationCount();
      System.out.println("Executing count: " + currentCount);
   }
   @BeforeTest
   public void setOutputDirectory(ITestContext context) {
      TestRunner runner = (TestRunner) context;
      String path=System.getProperty("user.dir");
      runner.setOutputDirectory(path+"/output-testng");
   }
}

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"/>ng="testng">
      </classes>
   </test>
</suite>

輸出

Thread ID: 12
Executing count: 0
===============================================
Suite1
Total tests run: 1, Passes: 1, Failures: 0, Skips: 0
===============================================

更新於:2022年1月12日

2K+ 次瀏覽

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告