5

I'm using TestNG to run Selenium based tests in Java. I have a bunch of repeated tests. Generally, they do all the same except of test name and one parameter.

I want to automate generation of it. I was thinking about using factory. Is there a way to generate tests with different name? What would be the best approach to this?

As for now I have something like below and I want to create 10 tests like LinkOfInterestIsActiveAfterClick

@Test(dependsOnGroups="loggedin")
public class SmokeTest extends BrowserStartingStoping{

public void LinkOfInterestIsActiveAfterClick(){
        String link = "link_of_interest";
        browser.click("*",link);
        Assert.assertTrue(browser.isLinkActive(link));
    }

}
  • My XML suite is auto-generated from Java code.
  • Test names are crucial for logging which link is active, and which one is not.
Urszula Karzelek
  • 556
  • 6
  • 15
  • possible duplicate of [Names for dynamically generated TestNG tests in Eclipse plugin](http://stackoverflow.com/questions/12257387/names-for-dynamically-generated-testng-tests-in-eclipse-plugin) – Nathan Sep 02 '15 at 00:59

2 Answers2

8

Have your test class implement org.testng.ITest and override getTestName() to return the name you want.

Mariusz Jamro
  • 30,615
  • 24
  • 120
  • 162
Cedric Beust
  • 15,480
  • 2
  • 55
  • 55
2

So I connected Factory with DataProvider and used attributes of contexts.

@DataProvider(name = "DP1")
public Object[][] createData() {
  Object[][] retObjArr={
  {"Link1","link_to_page"},
  {"Link2","link_to_page"},
  return retObjArr;
}

@Test (dataProvider = "DP1")
public void isActive(String name, String link){
  this.context.setAttribute("name", name);
  browser.click(link);
  Assert.assertTrue(browser.isLinkActive(link));
}

And in the Listener

public class MyListener extends TestListenerAdapter{
  @Override
  public void onTestSuccess(ITestResult tr){
    log("+",tr);
  }
  //and similar

  private void log(String string, ITestResult tr){
    List<ITestContext> k = this.getTestContexts();
    String testName = tr.getTestClass().getName();      
    for (ITestContext i: k)
    {
      if (i.getAttribute("name") != null)
        logger.info(testName+"."+i.getAttribute("name"));
    }
  }

}
Urszula Karzelek
  • 556
  • 6
  • 15
  • @djangofan Sorry, but I don't have the code anymore. (answered over 4 years ago) – Urszula Karzelek Jul 30 '14 at 15:42
  • Ok, well I can tell you that the solution you posted as an answer here does not actually work. Now, if you actually showed a Factory generating separate classes, then I believe it would work. Setting test name on tests generated from a DataProvider does not work because the class instance shares the test name between the multiple parameterized calls of the class. – djangofan Jul 30 '14 at 18:26