【问题标题】:TestNG pass command line arguments to testng.xml from java main methodTestNG 将命令行参数从 java main 方法传递给 testng.xml
【发布时间】:2021-08-30 06:54:21
【问题描述】:

我在我的 testng.xml 文件中使用这样的参数

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

但我希望该参数从我的 main 方法中获取命令行参数的值。

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

我该怎么做?

【问题讨论】:

    标签: java testng testng.xml


    【解决方案1】:

    您可以使用@BeforeSuite 方法和ITestContext 作为参数从代码中添加参数(将由testng 自动注入)。无需更改main 方法。

    Before 套件方法将在任何测试方法执行之前运行。

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

    编辑:当命令行参数被用作参数时

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

    现在将beforeMethod 更新为:

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

    【讨论】:

    • 我需要它在 Main 类中,因为我需要使用命令行参数。而@BeforeSuite 不会在那种情况下运行。
    • @mr_olaznog 你仍然可以和@987654328一起使用它@我会更新答案
    • @mr_olaznog 希望更新的答案能解决问题。
    • beforeSuite 方法不运行。它仅在其中一个测试类中运行。
    猜你喜欢
    • 2017-06-06
    • 2010-12-11
    • 1970-01-01
    • 2012-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-26
    • 1970-01-01
    相关资源
    最近更新 更多