使用 TestNG
配置 TestNG
要开始使用 TestNG,请在您的项目中包含以下依赖项(将版本替换为您希望使用的版本):
<dependencies> [...] <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>6.3.1</version> <scope>test</scope> </dependency> [...] </dependencies>
如果您使用的是旧版本的 TestNG (<= 5.11),则依赖项将如下所示:
<dependencies> [...] <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>6.3.1</version> <scope>test</scope> <classifier>jdk15</classifier> </dependency> [...] </dependencies>
注意:如果您在 TestNG 测试中使用 JDK 1.4 Javadoc 注释,请将分类器jdk15替换为上面的jdk14。
这是开始所需的唯一步骤 - 您现在可以在测试源目录中创建测试(例如,src/test/java。只要使用默认值命名它们,例如*Test.java,它们就会运行由 Surefire 作为 TestNG 测试。
如果您想使用不同的命名方案,您可以更改包含参数,如测试的包含和排除示例中所述。
使用套件 XML 文件
另一种选择是使用 TestNG 套件 XML 文件。这允许灵活配置要运行的测试。这些文件以正常方式创建,然后添加到 Surefire 插件配置中:
<plugins> [...] <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.12.4</version> <configuration> <suiteXmlFiles> <suiteXmlFile>testng.xml</suiteXmlFile> </suiteXmlFiles> </configuration> </plugin> [...] </plugins>
此配置将覆盖包含和排除模式并运行套件文件中的所有测试。
指定测试参数
您的 TestNG 测试可以接受带有 @Parameters 注释的参数。您还可以将参数从 Maven 传递到您的 TestNG 测试,方法是将它们指定为系统属性,如下所示:
<plugins> [...] <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.12.4</version> <configuration> <systemPropertyVariables> <propertyName>firefox</propertyName> </systemPropertyVariables> </configuration> </plugin> [...] </plugins>
有关在 Surefire 测试中设置系统属性的更多信息,请参阅系统属性。
使用组
TestNG 允许您对测试进行分组。然后,您可以执行一个或多个特定组。要使用 Surefire 执行此操作,请使用groups参数,例如:
<plugins> [...] <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.12.4</version> <configuration> <groups>functest,perftest</groups> </configuration> </plugin> [...] </plugins>
同样,excludedGroups参数可用于运行除特定组之外的所有组。
并行运行测试
TestNG 允许您并行运行测试,包括 JUnit 测试。为此,您必须设置并行参数,如果默认值 5 不够,可以更改threadCount参数。例如:
</plugins> [...] <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.12.4</version> <configuration> <parallel>methods</parallel> <threadCount>10</threadCount> </configuration> </plugin> [...] </plugins>
这对于可能具有高并发性的慢速测试特别有用,或者快速粗略地评估测试和代码的独立性和线程安全性。
使用自定义侦听器和报告器
TestNG 支持将自定义侦听器、报告器、注释转换器和方法拦截器附加到您的测试。默认情况下,TestNG 附加了一些基本的侦听器来生成 HTML 和 XML 报告。
您可以像这样配置多个自定义侦听器:
</plugins> [...] <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.12.4</version> <configuration> <properties> <property> <name>usedefaultlisteners</name> <value>false</value> <!-- disabling default listeners is optional --> </property> <property> <name>listener</name> <value>com.mycompany.MyResultListener,com.mycompany.MyAnnotationTransformer,com.mycompany.MyMethodInterceptor</value> </property> <property> <name>reporter</name> <value>listenReport.Reporter</value> </property> </properties> </configuration> </plugin> [...] </plugins>
有关 TestNG 的更多信息,请参阅TestNG 网站。