在 TestNG 中,帶有優先順序的測試執行順序是什麼?


一個 TestNG 類可以包含不同的測試,例如 **test1、test2、test3** 等。當用戶執行包含各種測試的 TestNG 類時,它會根據提供的名稱按字母順序執行測試用例。但是,使用者可以為這些測試分配優先順序,以便這些測試可以按照使用者的優先順序執行。優先順序從“**0**”開始,這是最高優先順序,數字越大,優先順序越低。

在本文中,讓我們分析 TestNG 中帶優先順序的執行順序是如何工作的。

場景 1

如果 **test2** (優先順序=0)、**test1** (優先順序=1)、**test3** (優先順序=2),則 **test2** 將首先執行,然後是 **test1**,依此類推,基於優先順序。

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

  • **步驟 1** - 匯入 org.testng.annotations.Test 用於 TestNG。

  • **步驟 2** - 編寫註釋為 **@test**

  • **步驟 3** - 為 **@test** 註釋建立一個方法,名為 **test1**,優先順序為 **1**。

  • **步驟 4** - 分別對 **test2** 和 **test3** 重複這些步驟,優先順序為“0”和“2”。

  • **步驟 5** - 現在建立 **testNG.xml**。

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

示例

以下程式碼建立一個 TestNG 類並顯示執行的優先順序順序

import org.testng.annotations.Test;
public class OrderofTestExecutionInTestNG {
   @Test(priority=1)
   public void test1() {
      System.out.println("Starting execution of TEST1");
   }
   @Test(priority=0)
   public void test2() {
      System.out.println("Starting execution of TEST2");
   }
   @Test(priority=2)
   public void test3() {
      System.out.println("Starting execution of TEST3");
   }

}

輸出

Starting execution of TEST2
Starting execution of TEST1
Starting execution of TEST3

場景 2

如果 **test2** (優先順序=0)、**test1**(優先順序=1) 和 **test3** 沒有優先順序,則 **test2** 將首先執行,然後是 **test3**,最後是 **test1**。由於 **test3** 沒有使用者定義的優先順序,TestNG 將其優先順序設定為 0,並且按字母順序,**test2** 首先,然後是 **test3**。

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

  • **步驟 1** - 匯入 org.testng.annotations.Test 用於 TestNG。

  • **步驟 2** - 編寫註釋為 **@test**

  • **步驟 3** - 為 **@test** 註釋建立一個方法,名為 **test1**,優先順序為 1。

  • **步驟 4** - 對 **test2** 和 **test 3** 重複這些步驟,優先順序為 0,並且不提供任何優先順序。

  • **步驟 5** - 現在建立 **testNG.xml**。

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

示例

使用以下程式碼建立一個 TestNG 類並顯示執行的優先順序順序:

import org.testng.annotations.Test;
public class OrderofTestExecutionInTestNG {
   @Test(priority=1)
   public void test1() {
      System.out.println("Starting execution of TEST1");
   }
   @Test(priority=0)
   public void test2() {
      System.out.println("Starting execution of TEST2");
   }
   @Test()
   public void test3() {
      System.out.println("Starting execution of TEST3");
   }

}

輸出

Starting execution of TEST2
Starting execution of TEST3
Starting execution of TEST1

更新於:2022年3月9日

3K+ 次瀏覽

啟動您的 職業生涯

透過完成課程獲得認證

開始學習
廣告