Search code examples
javatestngtestng.xml

TestNG pass command line arguments to testng.xml from java main method


I am using parameters in my testng.xml file like this

<parameter name="name" value="value" />

But I want that parameter to get the value of a command line argument from my main method.

public static void main(String[] args) {
    TestNG runner = new TestNG();
    List<String> suitefiles = new ArrayList<String>();
    suitefiles.add(args[0]);
    runner.setTestSuites(suitefiles);
    runner.run();
}

How can I do it?


Solution

  • You can add the parameters from the code using @BeforeSuite method along with ITestContext as an argument(which would be automatically injected by testng). No need to change the main method.

    Before suite method would be run before any test method is executed.

    @BeforeSuite
    public void beforeSuite(ITestContext ctx) {
        Map<String, String> paramMap = ctx.getSuite().getXmlSuite().getParameters();
        // put all parameters.
        map.put("name","value");
    }
    

    EDIT: When command line arguments to be used as parameters

    public class MyTest {
        // use this map to store the parsed params from command line.
        private static Map<String, String> paramMap = new HashMap<>();
        
        public static void main(String[] args) {
            // parse args and put to paramMap
            paramMap.put(args[1],args[2]);
            TestNG runner = new TestNG();
            List<String> suitefiles = new ArrayList<String>();
            suitefiles.add(args[0]);
            runner.setTestSuites(suitefiles);
            runner.run();
        }
    }
    

    Now update the beforeMethod as:

    @BeforeSuite
    public void beforeSuite(ITestContext ctx) {
        Map<String, String> paramMap = ctx.getSuite().getXmlSuite().getParameters();
        // put all parameters.
        map.putAll(paramMap);
    }