如何在TestNG中執行多個測試類?


**testng.xml** 的格式為 **<classes>**,我們在這裡定義所有應該執行的測試類。使用者可以在需要執行的 **testng.xml** 中提及 n 個類。在本文中,我們將討論如何使用單個 **testng.xml** 執行多個類。

這裡,我們將有兩個包含多個測試方法的類,我們將看到如何配置 **testng.xml** 來執行這兩個類 - **NewTestngClass** 和 **OrderofTestExecutionInTestNG**。

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

  • **步驟 1** - 建立兩個 TestNG 類 - NewTestngClass 和 OrderofTestExecutionInTestNG。

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

  • **步驟 3** - 現在建立如下所示的 **testng.xml**。

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

示例

以下程式碼顯示瞭如何執行多個類:

src/ NewTestngClass.java

import org.testng.annotations.Test;
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");
   }
}

src/OrderofTestExecutionInTestNG.java

import org.testng.annotations.Test;
public class OrderofTestExecutionInTestNG {
   // test case 1
   @Test
   public void testCase3() {
      System.out.println("in test case 3 of OrderofTestExecutionInTestNG");
   }
   // test case 2
   @Test
   public void testCase4() {
      System.out.println("in test case 4 of OrderofTestExecutionInTestNG");
   }
}

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" />
         <class name = "OrderofTestExecutionInTestNG" />
      </classes>
   </test>
</suite>

輸出

in test case 1 of NewTestngClass
in test case 2 of NewTestngClass
in test case 3 of OrderofTestExecutionInTestNG
in test case 4 of OrderofTestExecutionInTestNG
===============================================
Suite1
Total tests run: 4, Passes: 4, Failures: 0, Skips: 0
===============================================

更新於:2022年1月12日

12K+ 次瀏覽

啟動您的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.