如何在 TestNG 中執行測試組?
組測試是 TestNG 中一項新的創新功能,在 JUnit 框架中不可用。它允許您將方法劃分為適當的部分,並執行測試方法的複雜分組。
您不僅可以宣告屬於組的方法,還可以指定包含其他組的組。然後,可以呼叫 TestNG 並要求它包含一組特定的組(或正則表示式),同時排除其他組。
組測試在您劃分測試的方式上提供了最大的靈活性。如果您想連續執行兩組不同的測試,則無需重新編譯任何內容。
組是在您的 **testng.xml** 檔案中使用 **<groups>** 標籤指定的。它可以在 **<test>** 或 **<suite>** 標籤下找到。在 **<suite>** 標籤中指定的組適用於其下的所有 **<test>** 標籤。
現在,讓我們來看一個示例,瞭解組測試是如何工作的。
解決此問題的方法/演算法 -
**步驟 1** - 建立兩個 TestNG 類 - **NewTestngClass** 和 **OrderofTestExecutionInTestNG**。
**步驟 2** - 在這兩個類中編寫兩種不同的 **@Test** 方法:**NewTestngClass** 和 **OrderofTestExecutionInTestNG**。
**步驟 3** - 如程式碼檔案中所示,將每個 @Test 標記為組。
**步驟 4** - 現在建立如下所示的 **testNG.xml** 來執行具有組名稱 **functest** 的 **@Test** 。
**步驟 5** - 執行 **testNG.xml** 或直接在 IDE 中執行 TestNG 類,或者使用命令列編譯並執行它。
**步驟 6** - 根據給定的配置,它將執行 **NewTestngClass** 的測試用例 1 和 **OrderofTestExecutionInTestNG** 類的兩個測試用例。
示例
以下程式碼展示瞭如何執行測試組 -
src/ NewTestngClass.java
import org.testng.annotations.Test; public class NewTestngClass { @Test(groups = { "functest", "checkintest" }) public void testCase1() { System.out.println("in test case 1 of NewTestngClass"); } @Test(groups = {"checkintest" }) public void testCase2() { System.out.println("in test case 2 of NewTestngClass"); } }
src/OrderofTestExecutionInTestNG.java -
import org.testng.annotations.Test; public class OrderofTestExecutionInTestNG { // test case 1 @Test(groups = { "functest" }) public void testCase3() { System.out.println("in test case 3 of OrderofTestExecutionInTestNG"); } // test case 2 @Test(groups = { "functest", "checkintest" }) public void testCase4() { System.out.println("in test case 4 of OrderofTestExecutionInTestNG"); } }
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 = "functest" /> </run> </groups> <classes> <class name = "NewTestngClass" /> <class name = "OrderofTestExecutionInTestNG" /> </classes> </test> </suite>
輸出
in test case 1 of NewTestngClass in test case 3 of OrderofTestExecutionInTestNG in test case 4 of OrderofTestExecutionInTestNG =============================================== Suite1 Total tests run: 3, Passes: 3, Failures: 0, Skips: 0 ===============================================