1
votes

Is there any way to run TestNG test from another java class.

@Test
public void f(Integer n, String s) {
}

I need to run the same method in a single suite with different arguments.(Inside for loop)

Is it possible?

Also, I see that dataprovider method should return Object[][]. This works fine for methods with two arguments. Can we send more than two arguments??

@DataProvider
public Object[][] dp() {
    return new Object[][] { new Object[] { 1, "a" }, new Object[] { 2, "b" }, };
}

@Test(dataProvider = "dp")
public void f(Integer n, String s, char c, double d, String s2) {
}

I am trying to do it by using some TestNG classes

public static void main(String[] args) {

    List<XmlClass> classes = new ArrayList<>();
    classes.add(new XmlClass("com.test.PortalTest"));

    XmlSuite suite = new XmlSuite();
    suite.setName("Portal Test Suite");

    XmlTest test = null;
    for (int index = 0; index < 7; index++) {
        test = new XmlTest();
        test.setName("Portal Test - " + index);
        test.setXmlClasses(classes);
        test.addParameter("downloadFileIndex", String.valueOf(index));
        suite.addTest(test);
    }

    List<XmlSuite> suites = new ArrayList<XmlSuite>();
    suites.add(suite);

    TestListenerAdapter testListenerAdapter = new TestListenerAdapter();

    TestNG testNG = new TestNG();
    Class[] classesClasses = {PortalTest.class};
    testNG.setTestClasses(classesClasses);
    testNG.setXmlSuites(suites);
    testNG.addListener(testListenerAdapter);
    testNG.run();

    System.out.println("Passed : " + testListenerAdapter.getPassedTests());
    System.out.println("Failed : " + testListenerAdapter.getFailedTests());
    System.out.println("Skipped : " + testListenerAdapter.getSkippedTests());

}

I use below code to run method having @Test for one time. How can i run the @Test method multiple times in a same test.

TestListenerAdapter tla = new TestListenerAdapter();
TestNG testng = new TestNG();
testng.setTestClasses(new Class[] { PortalTest.class });
testng.addListener(tla);
testng.run();
1

1 Answers

0
votes
  1. TestNG test methods are always public so you can instantiate an instance of any test class from another test class and simply call the method you want from another test class.
  2. TestNG data providers must return either an array of arrays, Object[][], or an iterator of arrays, Iterator<Object[]>, so you can certainly use as many (or as few) arguments as you'd like.

e.g.

@DataProvider
public Object[][] dp() {
    return new Object[][] {
            new Object[] { 1, "a", 'x', 3.14, "pi" },
            new Object[] { 2, "b", 'y', 6.28, "tau" },
    };
}

@Test(dataProvider = "dp")
public void f(Integer n, String s, char c, double d, String s2) {
    new OtherTestClass().f(n, s);
}