如何在 TestNG.xml 中保持執行順序?


在最新版本中,TestNG 按 TestNG.xml 或任何可執行 XML 檔案中提到的順序執行類。但是,有時在舊版本中執行 tesng.xml 時,順序不會被採納。TestNG 可能會以隨機順序執行類。在最新版本中,TestNG 按 TestNG.xml 或任何可執行 XML 檔案中提到的順序執行類。但是,有時在舊版本中執行 tesng.xml 時,順序不會被採納。TestNG 可能會以隨機順序執行類。

在本文中,我們將討論如何確保執行順序按照 tesng.xml 保持不變。

TestNG 支援兩個屬性 - parallel 和 preserve-order。這些屬性用於 testing.xml 中。

  • Parallel 屬性用於並行執行測試。因此,第一個檢查是確保執行不是並行發生的以保留執行順序。Parallel 屬性在套件級別提及,因此新增 parallel = "none" 而不是 parallel=""。

  • Preserver-order 屬性在測試級別使用。TestNG 在舊的 jar 中預設將該值設定為 false。這可能導致隨機執行。為了確保執行順序被採納,我們在 testing.xml 中將該屬性設定為 true。

現在,我們將瞭解如何實現這兩個屬性以確保執行順序按照 testing.xml 保持不變。

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

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

  • 步驟 2:在每個類(OrderofTestExecutionInTestNG 和 NewTestngClass)中編寫兩個不同的 @Test 方法。

  • 步驟 3:現在建立 testNG.xml 來執行這兩個 TestNG 類,並按如下所示提及 parallel=none 和 preserve-order=true

  • 步驟 4:現在,執行 testNG.xml 或 IDE 中直接執行 TestNG 類,或者使用命令列編譯並執行它。

示例

以下程式碼適用於 TestNG 類 - OrderofTestExecutionInTestNG

import org.testng.annotations.*;

public class OrderofTestExecutionInTestNG {
    // test case 1
    @Test
    public void testCase1() {
        System.out.println("in test case 1 of OrderofTestExecutionInTestNG");
    }
    // test case 2
    @Test
    public void testCase2() {
        System.out.println("in test case 2 of OrderofTestExecutionInTestNG");
    }
 }   

以下程式碼適用於通用 TestNG 類 - NewTestngClass

import org.testng.annotations.*;

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");
    }
} 

testng.xml

這是一個配置檔案,用於組織和執行 TestNG 測試用例。

當只需要執行有限的測試而不是完整套件時,它非常方便。

<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

<suite name = "Suite1" parallel = "none">
   <test name = "test1" preserve-order = "true">
      <classes>
         <class name = "OrderofTestExecutionInTestNG"/>
    <class name = "NewTestngClass"/>
      </classes>
   </test>
</suite>

輸出

in test case 1 of OrderofTestExecutionInTestNG
in test case 2 of OrderofTestExecutionInTestNG
in test case 1 of NewTestngClass
in test case 2 of NewTestngClass

===============================================
Suite1
Total tests run: 4, Passes: 4, Failures: 0, Skips: 0
=============================================== 

更新於: 2023-08-16

814 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.