TestNG 如何使用多執行緒呼叫測試方法?
TestNG 支援多執行緒,即 @Test 方法可以並行多次呼叫。需要從多個執行緒呼叫測試方法,以便也需要多次呼叫。如果我們想在多執行緒中執行單個 @Test,則沒有用。因此,如果需要非同步多次執行 @Test 方法,則多執行緒很有用。
可以透過在 @Test 中使用關鍵字 **threadPoolSize =** 來實現多執行緒。但是,要多次呼叫方法,還需要另一個關鍵字 **invocationCount =**。結合這兩個關鍵字,我們可以實現多執行緒。例如,
@Test(threadPoolSize=5, invocationCount = 10)
在此示例中,@Test 方法將從 5 個執行緒中總共執行 10 次。請注意,從 5 個不同執行緒中總執行次數為 10。這並不意味著 @Test 將在每個執行緒中總共執行 50 次或 10 次。它僅僅意味著 5 個執行緒將總共執行該方法 10 次。
在本文中,我們將說明如何在 TestNG 中實現多執行緒。
解決此問題的方法/演算法 -
步驟 1 - 建立一個名為 NewTestngClass 的 TestNG 類。
步驟 2 - 在類中編寫一個 @Test 方法,如程式程式碼部分所示。新增 **threadPoolSize** 和 **invocationCount**
步驟 3 - 現在建立 testNG.xml 來執行 TestNG 類。
步驟 4 - 執行 testNG.xml 或直接在 IDE 中執行 TestNG 類,或者使用命令列編譯並執行它。
在輸出中,您可以注意到有 5 個執行緒並行執行(執行緒 ID 12 到 16),並且該方法總共運行了 10 次。
示例
對常用的 TestNG 類“NewTestngClass”使用以下程式碼 -
src/ NewTestngClass.java
import org.testng.ITestContext;
import org.testng.annotations.*;
public class NewTestngClass {
@Test(threadPoolSize = 5, invocationCount = 10)
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);
}
}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"> <classes> <class name = "NewTestngClass"/> </classes> </test> </suite>
輸出
Thread ID: 12 Thread ID: 13 Thread ID: 16 Thread ID: 14 Executing count: 0 Thread ID: 15 Executing count: 0 Executing count: 0 Executing count: 0 Executing count: 0 Thread ID: 15 Executing count: 5 Thread ID: 12 Executing count: 6 Thread ID: 13 Executing count: 7 Thread ID: 14 Executing count: 8 Thread ID: 15 Executing count: 9 =============================================== Suite1 Total tests run: 10, Passes: 10, Failures: 0, Skips: 0 ===============================================================
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP