TestNG中依次執行測試方法?


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

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

場景1

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

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

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

  • 步驟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:為TestNG匯入org.testng.annotations.Test。

  • 步驟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

更新於:2023年8月18日

579 次檢視

啟動您的職業生涯

透過完成課程獲得認證

開始
廣告