如何在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