如何将动态参数传递给testNG.xml运行多个测试

时间:2019-02-06 15:20:22

标签: java testng testng.xml

我有xml套件,可以发送多个测试和多个参数。

示例:

        <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>

我需要多次使用不同的offerId参数运行此类。 (例如1234,4567,7899)

我只希望运行一次此请求,它将激怒所有不同的参数,并一次又一次运行全服,并在同一报告中给出结果。

这就是我所做的:

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

}

因此这将加载并运行我需要的西装,但是如何在套件中更改参数? (之后,我将创建for循环)

[当前,我复制了xml,并手动更改了每个测试的参数。然后运行套件套件]

测试:

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

2 个答案:

答案 0 :(得分:1)

在这种情况下,您可以使用dataprovider或从excel读取值,然后将针对dataprovider / excel工作表中的每个值运行测试。
提供一个示例,说明如何在测试用例中使用dataprovider。

git push --force origin develop

因此,上面的测试将运行3次,对于数据提供程序中存在的每个值一次,并且您不需要在testng xml中进行任何参数化。您只需要提及类名,所有测试将自动运行。您的testng.xml应该像这样:

@DataProvider(name = "offerId")
public static Object[][] voiceSearchTestData() {
    return new Object[][]{
            {1234},
            {2345},
            {4567}
    };
}

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

答案 1 :(得分:0)

以下代码的作用: 我想在运行时为每个参数添加一个参数列表。这些参数作为maven运行时参数传递。可以使用System.getProperty()方法读取它们,如下所示。然后将这些参数添加到<test>内的<suite>中,并成功运行testng。这在其他情况下也非常有用。

下面的代码读取testng.xml文件并将参数添加到

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();
相关问题