如何在 TestNG 測試用例中指定類級組?


組測試是 TestNG 中一個新的創新功能,在 JUnit 框架中不存在。它允許您將方法劃分為適當的部分,並執行測試方法的複雜分組。

您不僅可以宣告屬於組的方法,還可以指定包含其他組的組。然後,可以呼叫 TestNG 並要求其包含一組特定的組(或正則表示式),同時排除另一組。

組測試在您如何劃分測試方面提供了最大的靈活性,並且如果您想連續執行兩組不同的測試,則不需要重新編譯任何內容。即使組也可以在類級別提及,因此所有測試都將執行屬於同一組的類的測試。

組在您的 testng.xml 檔案中使用 <groups> 標籤指定。它可以在 <test> 或 <suite> 標籤下找到。在 <suite> 標籤中指定的組適用於下面的所有 <test> 標籤。

現在,讓我們舉一個例子來看看組測試是如何工作的。

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

  • 步驟 1:建立 TestNG 類 - NewTestngClass

  • 步驟 2:在類中編寫 3 個不同的 @Test 方法 - NewTestngClass

  • 步驟 3:按照程式碼檔案中提到的方法,為每個 @Test 新增組標記。

  • 步驟 4:在類名前面,類頂部寫上組名,如程式部分所示。

  • 步驟 5:現在建立如下所示的 testNG.xml 以執行組名為 GlobalGroup 的 @Test。它是類級組名。

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

  • 步驟 7:根據給定的配置,它將執行 NewTestngClass 的所有 3 個測試用例。

示例

以下程式碼展示瞭如何執行測試組

src/ NewTestngClass.java

import org.testng.annotations.Test;

@Test(groups = { "GlobalGroup" })
public class NewTestngClass {

    @Test(groups = { "unit", "integration" })
    public void testCase1() {
        System.out.println("in test case 1 of NewTestngClass");
    }
    @Test(groups = { "integration" })
    public void testCase2() {
        System.out.println("in test case 2 of NewTestngClass");
    }
    @Test(groups = { "unit" })
    public void testCase3() {
        System.out.println("in test case 3 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">
   <test name = "test1">
<groups>
         <run>
            <include name = "GlobalGroup" />
         </run>
      </groups>
      <classes>
    <class name = "NewTestngClass" />
</classes>
   </test>
</suite>

輸出

in test case 1 of NewTestngClass
in test case 2 of NewTestngClass
in test case 3 of NewTestngClass
===== Invoked methods
    newTest.testCase1()[pri:0, instance:newTest@7946e1f4]
    newTest.testCase2()[pri:0, instance:newTest@7946e1f4]
    newTest.testCase3()[pri:0, instance:newTest@7946e1f4]
=====

===============================================
suite
Total tests run: 3, Passes: 3, Failures: 0, Skips: 0
===============================================

更新於: 2023-08-18

108 次檢視

啟動您的 職業生涯

透過完成課程獲得認證

開始學習
廣告