简体   繁体   中英

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?

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM