How to set Thread name in TestNG?

TestNGRest AssuredDynamic Programming

TestNG supports multithreading, i.e., a @Test method can be invoked multiple times in parallel. TestNG by default assigns the integer ID to the thread. Sometimes, it is required to debug for a specific thread or create custom report for a user-provided thread name. In such a scenario, setting up the thread name is good before execution to easily identify the executed tests/steps.

In this article, we will illustrate how to set thread name as user input.

Approach/Algorithm to solve this problem

  • Step 1 − Create a TestNG class, NewTestngClass.

  • Step 2 − Write a @Test method in the class NewTestngClass as shown in the programming code section below.

  • Step 3 − Write @BeforeMethod as shown in the programming code. Fetch the default thread name and then set up a new value to the thread.

  • Step 4 − Now create the testNG.xml as given below to run the TestNG classes.

  • Step 5 − Finally, run the testNG.xml or directly testNG class in IDE or compile and run it using command line.

In the output, the user will see the new name of the thread.

Example

Use the following code for the common TestNG class, 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

This is a configuration file that is used to organize and run the TestNG test cases. It is very handy when limited tests are needed to execute rather than the full suite.

<?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>

Output

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
===============================================
raja
Updated on 12-Jan-2022 12:42:37

Advertisements