Search code examples
javatestngtestng.xml

How to pass dynamic parameter TO testNG.xml run multiple tests


I have xml suite that sends multiple tests and multiple parameters.

example:

        <test name="Create">       
        <classes>       
        <class name="TestClass">
            <methods>
                <parameter name="offerId" value="1234"/>
                <include name="testmethod"/>
            </methods>
        </class>                                          
      </classes>
      </test>
        <test name="Add">       
        <classes>       
        <class name="TestClass2">
            <methods>
                <include name="testmethod2"/>
            </methods>
        </class>                                          
      </classes>
      </test>

I need to run this class multiple times, each time with different offerId parameter. (e.g 1234,4567,7899)

I want to run this request only once, and it will irritate over all different parameter and run the whole suit again and again, and give result on the same report.

this is what I did:

@Test
public void runSuites2(){

    TestNG testng = new TestNG();
    List<String> suites=new ArrayList<String>();
    suites.add("c:/tests/testng1.xml");//path to xml..

    testng.setTestSuites(suites);
    testng.run();

}

so this will load and run the suit I need, but how to change the parameter inside the suite? (after it I will create for loop)

[currently I duplicated the xml and manually change the parameter for each test. and then run suite-of-suites]

the test:

@Parameters({ "offerId" })
@Test
public void testmethod(String offerId, ITestContext context) throws Exception {
    Reporter.log("offer ID is = " + offerId, true);
        }

Solution

  • What the below code does: I want to add a list of parameters to each during runtime. These parameters are passed as maven runtime arguments. They are read using System.getProperty() method as shown below. Then these parameters are added to the <test> inside <suite> and testng is ran successfully. This can be really useful in other scenarios as well.

    The below code reads the testng.xml file and adds parameter to

    List<String> parameters = new ArrayList<>();
    parameters = Arrays.asList(System.getProperty("parameters").split(",");
    
    TestNG tng = new TestNG();
    File initialFile = new File("testng.xml");
    InputStream inputStream = FileUtils.openInputStream(initialFile);
    Parser p = new Parser(inputStream);
    List<XmlSuite> suites = p.parseToList();
    for(XmlSuite suite:suites){
        List<XmlTest> tests = suite.getTests();
        for (XmlTest test : tests) {
             for (int i = 0; i < parameters.size(); i++) {
                HashMap<String, String> parametersMap = new HashMap<>();
                parametersMap.put("parameter",parameters.get(i));
                test.setParameters(parametersMap);
            }
        }
    }
    tng.setXmlSuites(suites);
    tng.run();