在 TestNG 中,執行緒數到底有什麼作用?
TestNG 支援多執行緒,即 **@Test** 方法可以並行呼叫。可以從多個執行緒呼叫一個或多個測試方法。因此,如果需要非同步並行執行 **@Test** 方法,多執行緒非常有用。
可以使用關鍵字 **"thread-count=<整數>" 在 Testng.xml 檔案中實現多執行緒。執行緒數基本上是同時或並行執行多個測試的例項數量。**thread-count** 屬性允許使用者指定應為本次執行執行多少個執行緒。
在本文中,我們將說明如何實現多執行緒。
解決此問題的方法/演算法
在這個例子中,五個 **@Test** 方法將從五個不同的執行緒並行執行。
**步驟 1** - 建立一個 TestNG 類,**NewTestngClass**。
**步驟 2** - 在 **NewTestngClass** 類中編寫五個 @Test 方法,如程式設計程式碼部分所示。
**步驟 3** - 現在建立如下所示的 **testng.xml** 來執行 TestNG 類。新增 **thread-count** 和 **parallel** 關鍵字。
**步驟 4** - 最後,執行 **testng.xml** 或直接在 IDE 中執行 TestNG 類,或者使用命令列編譯並執行它。
在輸出中,使用者可以看到總共五個執行緒並行執行 – **ID 18 到 22**。
示例
使用以下程式碼作為通用的 TestNG 類,**NewTestngClass**:
src/ NewTestngClass.java
import org.testng.ITestContext; import org.testng.annotations.*; public class NewTestngClass { @Test() public void testcase1(ITestContext testContext){ System.out.println("Thread ID: "+Thread.currentThread().getId()); int currentCount = testContext.getAllTestMethods()[0].getCurrentInvocationCount(); System.out.println("Executing count: " + currentCount); } @Test() public void testcase2(ITestContext testContext){ System.out.println("Thread ID:"+Thread.currentThread().getId()); int currentCount = testContext.getAllTestMethods()[1].getCurrentInvocationCount(); System.out.println("Executing count: " + currentCount); } @Test() public void testcase3(ITestContext testContext){ System.out.println("Thread ID:"+Thread.currentThread().getId()); int currentCount = testContext.getAllTestMethods()[2].getCurrentInvocationCount(); System.out.println("Executing count: " + currentCount); } @Test() public void testcase4(ITestContext testContext){ System.out.println("Thread ID: "+Thread.currentThread().getId()); int currentCount = testContext.getAllTestMethods()[3].getCurrentInvocationCount(); System.out.println("Executing count: " + currentCount); } @Test() public void testcase5(ITestContext testContext){ System.out.println("Thread ID: "+Thread.currentThread().getId()); int currentCount = testContext.getAllTestMethods()[4].getCurrentInvocationCount(); System.out.println("Executing count: " + currentCount); } }
testng.xml
這是一個配置檔案,用於組織和執行 TestNG 測試用例。當只需要執行有限的測試而不是完整的套件時,它非常方便。
<?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" > <suite name = "Suite1" thread-count="5" parallel="methods"> <test name = "test1"> <classes> <class name = "NewTestngClass"/> </classes> </test> </suite>
輸出
Thread ID: 18 Thread ID: 22 Thread ID: 19 Executing count: 0 Thread ID: 20 Executing count: 0 Thread ID: 21 Executing count: 0 Executing count: 0 Executing count: 0 =============================================== Suite1 Total tests run: 5, Passes: 5, Failures: 0, Skips: 0 ===============================================
廣告