如何在TestNG中設定執行緒名稱?
TestNG 支援多執行緒,即一個 @Test 方法可以並行多次呼叫。TestNG 預設將整數 ID 分配給執行緒。有時,需要除錯特定執行緒或為使用者提供的執行緒名稱建立自定義報告。在這種情況下,在執行之前設定執行緒名稱以便輕鬆識別執行的測試/步驟是一個好方法。
在本文中,我們將說明如何將執行緒名稱設定為使用者輸入。
解決此問題的方法/演算法
步驟 1 − 建立一個 TestNG 類,NewTestngClass。
步驟 2 − 在類 NewTestngClass 中編寫一個 @Test 方法,如下面的程式設計程式碼部分所示。
步驟 3 − 編寫 @BeforeMethod,如下面的程式設計程式碼所示。獲取預設執行緒名稱,然後為執行緒設定新值。
步驟 4 − 現在建立如下所示的 testNG.xml 來執行 TestNG 類。
步驟 5 − 最後,執行 testNG.xml 或直接在 IDE 中執行 TestNG 類,或者使用命令列編譯並執行它。
在輸出中,使用者將看到執行緒的新名稱。
示例
對普通的 TestNG 類 NewTestngClass 使用以下程式碼 −
src/ NewTestngClass.java
import org.testng.annotations.*;
public class NewTestngClass {
@BeforeMethod
public void beforeMethod() {
String id = Thread.currentThread().getName();
System.out.println("Before test-method. Thread name is:" + id);
Thread.currentThread().setName("Test-Thread");
String newId = Thread.currentThread().getName();
System.out.println("Before test-method. Name of Thread after setting to new value is: " + newId);
}
@Test
public void testOne() {
String name = Thread.currentThread().getName();
System.out.println("Executing testOne. Thread name is: " + name);
}
}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>
輸出
Before test-method. Thread name is: main Before test-method. Name of Thread after setting to new value is: Test-Thread Executing testOne. Thread name is: Test-Thread =============================================== Suite1 Total tests run: 1, Passes: 1, Failures: 0, Skips: 0 ===============================================
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP