如何在 TestNG 中依次執行所有方法?
一個 TestNG 類可以包含不同的測試,例如 test1、test2、test3 等。一旦使用者執行包含各種測試的 TestNG 類,它就會根據提供的名稱按字母順序執行測試用例。但是,使用者可以為這些測試分配優先順序,以便這些測試可以根據使用者的優先順序執行。優先順序從 0 開始,並按遞增順序排列。優先順序 0 具有最高優先順序,並且當優先順序增加為 1、2、3 等時,優先順序會降低。
在本文中,讓我們分析執行順序以不同方式發生的情況。
場景 1
如果 test2(優先順序=0)、test1(優先順序=1)、test3(優先順序=2),則 test2 將首先執行,然後是 test1,依此類推,這取決於優先順序。
解決此問題的方法/演算法
步驟 1:匯入 org.testng.annotations.Test 用於 TestNG。
步驟 2:編寫一個註釋作為 @test
步驟 3:為 @test 註釋建立一個方法作為 test1 並提供優先順序=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(優先順序=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 重複步驟 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