5

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);
}
djangofan
  • 28,471
  • 61
  • 196
  • 289

3 Answers3

4

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

Cedric Beust
  • 15,480
  • 2
  • 55
  • 55
  • Thanks. I was thinking I might be able to set the test name from input coming from the DataProvider. I'll think about it now that I know its not straight forward. – djangofan Aug 27 '12 at 23:58
  • 1
    @Cedric I've tried using ITest, but the name does not change in the HTML report that gets generated, nor does it changes in the TestNG Eclipse plugin GUI. where am i going wrong public class TestNGNameTest implements ITest { Test public void test(ITestContext context) { System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName()); System.out.println("Test name : "+context.getName()); } Override public String getTestName() { System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName()); return "testOverridenName"; } } – Mrunal Gosar Aug 23 '14 at 14:35
3

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

isuru chathuranga
  • 995
  • 15
  • 24
0

I'm getting the error below, about the two parameters of BeforeMethod, what is wrong?

Message:

org.testng.TestNGException: Method initLog requires 2 parameters but 2 were supplied in the BeforeMethod annotation.

    @Parameters({"method", "FinancialKeys"})
    @BeforeMethod(alwaysRun = true)
    public void initLog(Method method, Object[] FinancialKeys) {...}