Testng 与 Maven 配合使用
在 Maven 项目中引入 Testng 框架
引入 Testng 依赖
在项目根目录下的 pom.xml
文件中引入:
<dependencies>
[...]
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.9.0</version>
<scope>test</scope>
</dependency>
[...]
</dependencies>
创建 Testng 测试套件文件
Testng 支持 xml
格式和 yaml 格式的套件文件,在这里使用 yaml
更易于阅读,要引入 yaml
格式的测试套件文件还需要额外引入 snakeyaml
依赖:
- 在项目根目录下的
pom.xml
文件中引入:
<dependencies>
[...]
<dependency>
<groupid>org.yaml</groupid>
<artifactid>snakeyaml</artifactid>
<version>2.2</version>
</dependency>
[...]
</dependencies>
- 创建
test/resources/testng.yaml
文件:
简单的示范,具体内容见 testng 文档:
name: SingleSuite
threadCount: 1
parameters: { message: "Hello World" }
tests:
- name: Demo
parameters: { count: 10 }
classes:
- net.guosx.TestDemo
- 使用 Maven Surefire 插件与 Testng 配合使用来运行 Testng:
Maven Surefire Plugin – Using TestNG
在项目根目录下的 pom.xml
文件中引入 Surefire 插件:
<build>
[...]
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.2.5</version>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>src/test/resources/testng.yaml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
</plugins>
[...]
</build>
<suiteXmlFile>xxx/testng.yaml</suiteXmlFile>
根据自己测试套件位置填写
运行 Testng 测试用例
- 创建一个简单的例子
public class TestDemo {
@Parameters({"message", "count"})
@Test
public void test(String message, int count) {
System.out.println("message: " + message);
System.out.println("count: " + count);
}
}
- 通过 Maven 运行:
mvn clean test
- 通过 Maven 将测试用例参数传递给 Testng 用例
在本例中,测试套件文件
testng.yaml
定义了parameters
测试参数,但是默认写死在文件中,如果需要在运行测试时动态传递,可以使用 Maven Surefire 插件的系统参数功能: Maven Surefire Plugin – Using System Properties
在 Surefire 插件中定义参数 systemPropertyVariables
:
格式为:
<systemPropertyVariables>
<propertyName>propertyValue</propertyName>
</systemPropertyVariables>
例如:
<build>
[...]
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.2.5</version>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>src/test/resources/testng.yaml</suiteXmlFile>
</suiteXmlFiles>
<systemPropertyVariables>
<message>Hello World!!!</message>
<count>10</count>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
[...]
</build>
运行测试用例的命令可以重写这些参数:
mvn clean test -Dmessage="Hello" -Dcount="100"