Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using TestNG, is it possible to dynamically change the test name?

Tags:

junit

testng

Using TestNG, is it possible to dynamically change the test name with a method such as this one below?

@Test(testName = "defaultName", dataProvider="tests")
public void testLogin( int num, String reportName )
{
    System.out.println("Starting " + num + ": " + reportName);
    changeTestName("Test" + num);
}
like image 760
djangofan Avatar asked Aug 27 '12 18:08

djangofan


People also ask

How do you change your test name in TestNG?

First, create a Thread Local String object to store your test case name. private ThreadLocal<String> testName = new ThreadLocal<>(); Secondly, implement a BeforeMethod function to override your test name before the execution. Third, you need to implement ITest interface into your test.

What is @factory annotation in TestNG?

@Factory annotated method allows tests to be created at runtime depending on certain data-sets or conditions. The method must return Object[].

Can we run a test case multiple times in TestNG?

The Complete TestNG & Automation Framework Design CourseWe can execute a particular test method multiple times (say 5 times) with the help of the invocationCount helper attribute.


2 Answers

No, but your test class can implement org.testng.ITest and override getTestName() to return the name of your test.

like image 66
Cedric Beust Avatar answered Jan 03 '23 16:01

Cedric Beust


For anybody still facing this.
This can be done by implementing the org.testng.ITest class and overriding the getTestName() method just like as @Cedric mentions.
To make the test name dynamic you can use a locally created testName variable In addition.
Below is all you need to do

import java.lang.reflect.Method;
import org.testng.ITest;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;

public class MyTestClass implements ITest {

    @Test(dataProvider = "/* yourDataProvider */")
    public void myTestMethod() {
        //Test method body
    }

    @BeforeMethod(alwaysRun = true)
    public void setTestName(Method method, Object[] row) {
        //You have the test data received through dataProvider delivered here in row
        String name = resolveTestName(row);
        testName.set(name);
    }

    @Override
    public String getTestName() {
        return testName.get();
    }
    private ThreadLocal<String> testName = new ThreadLocal<>();
}

This way you should be able to generate the testName dynamically

like image 29
isuru chathuranga Avatar answered Jan 03 '23 18:01

isuru chathuranga