使用Maven命令行以编程方式运行TestNG

pra*_*eel 6 testng webdriver maven

我需要并行运行多个测试套件。一种方法是创建如下的套件文件-

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

<suite name="AllTests" verbose="8">
    <suite-files>
    <suite-file path="./Suite1.xml"></suite-file>
    <suite-file path="./Suite2.xml"></suite-file>
</suite-files>
</suite>
Run Code Online (Sandbox Code Playgroud)

创建一个如下所示的类-

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import org.testng.xml.Parser;
import org.testng.xml.XmlSuite;
import org.testng.TestNG;
import org.xml.sax.SAXException;

public class RunSuitesInParallel{

    public static void main(String[] args) throws FileNotFoundException, ParserConfigurationException, SAXException, IOException {
        TestNG testng = new TestNG(); 
        testng.setXmlSuites((List <XmlSuite>)(new Parser("src"+File.separator+"test"+File.separator+"resources"+File.separator+"xml_Suites"+File.separator+"AllTests.xml").parse()));       
        testng.setSuiteThreadPoolSize(2);
        testng.run();
    }
}
Run Code Online (Sandbox Code Playgroud)

当我从Eclipse IDE运行该代码时,可以实现上述目标。我如何从Maven命令行运行它?

POM.xml的片段-

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.14.1</version>
    <configuration>
        <include>com/shn/test/*Tests.class</include>
        <suiteXmlFiles>
            <!-- <suiteXmlFile>src/test/resources/TestNG.xml</suiteXmlFile> -->
            <suiteXmlFile>${tests}</suiteXmlFile>
        </suiteXmlFiles>
        <testFailureIgnore>true</testFailureIgnore>
    </configuration>
</plugin>
Run Code Online (Sandbox Code Playgroud)

当前执行我使用的任何给定的XML-

mvn -Dtests=AllTests.xml test
Run Code Online (Sandbox Code Playgroud)

khm*_*ise 1

并行运行测试的最简单解决方案是使用maven-surefire-plugin的配置,如下所示:

</plugins>
    [...]
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.15</version>
        <configuration>
          <parallel>methods</parallel>
          <threadCount>10</threadCount>
        </configuration>
      </plugin>
    [...]
</plugins>
Run Code Online (Sandbox Code Playgroud)

通常您不需要单独的 testng.xml 文件来运行测试,因为它们将根据测试的命名约定默认运行。此外,除了您给定的定义是错误的之外,不需要单独制定包含规则。

您可以通过 groups 参数控制与 TestNG 相关的测试,如下所示:

mvn -Dgroups=Group1 test
Run Code Online (Sandbox Code Playgroud)

此外,可以通过test属性控制哪些测试将运行,如下所示:

mvn -Dtest=MyTest test
Run Code Online (Sandbox Code Playgroud)

或者

mvn -Dtest=MyTest,FirstTest,SecondTest test
Run Code Online (Sandbox Code Playgroud)

从命令行指定测试的更细粒度的方法如下:

mvn -Dtest=MyTest#myMethod test
Run Code Online (Sandbox Code Playgroud)

myMethod它运行MyTest 类中的方法。