如何在 TestNG 中順序執行測試?


一個 TestNG 類可以包含不同的測試,例如 test1、test2、test3 等。當用戶執行包含各種測試的 TestNG 類時,它會根據提供的名稱按字母順序執行測試用例。但是,使用者可以為這些測試分配優先順序,以便這些測試可以根據使用者的優先順序執行。優先順序從 0 開始,並按遞增順序排列。優先順序 0 具有最高優先順序,當優先順序增加到 1、2、3 等時,優先順序會降低。

在本教程中,讓我們分析一下執行順序以不同方式發生的情況。

場景 1

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

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

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

  • 步驟 2:編寫一個 @test 註解。

  • 步驟 3:為 @test 註解建立一個方法,例如 test1,並提供 priority=1。

  • 步驟 4:分別為 test2 和 test3 重複步驟 3,優先順序分別為 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 (priority=0)、test1(priority=1) 並且 test3 沒有優先順序,則 test2 將首先執行,然後是 test3,最後是 test1。由於 test3 沒有使用者定義的優先順序,TestNG 將其優先順序設定為 0,並且在按字母順序排列時,test2 首先出現,然後是 test3。

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

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

  • 步驟 2:編寫一個 @test 註解。

  • 步驟 3:為 @test 註解建立一個方法,例如 test1,並提供 priority=1。

  • 步驟 4:分別為 test2 和 test 3 重複步驟 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

更新於:2023年8月18日

2K+ 次瀏覽

啟動您的 職業生涯

完成課程後獲得認證

開始學習
廣告