快速生成单元测试报告
1. 确保项目配置正确
在pom.xml中添加JUnit 5依赖:
xml复制代码
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.9.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.9.2</version>
<scope>test</scope>
</dependency>
</dependencies>
2. 配置Maven Surefire插件生成报告
在pom.xml的<build>部分添加插件配置:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M7</version>
<configuration>
<!-- 生成HTML格式报告 -->
<reportFormat>html</reportFormat>
<!-- 配置报告输出目录 -->
<reportsDirectory>target/surefire-reports</reportsDirectory>
</configuration>
</plugin>
</plugins>
</build>
3. 运行测试并生成报告
在项目根目录下执行Maven命令:mvn test
执行完成后,测试报告会生成在target/surefire-reports目录下,打开index.html即可查看详细的HTML格式测试报告。
4. (可选)生成代码覆盖率报告
使用JaCoCo插件生成代码覆盖率报告:
- 在
pom.xml中添加JaCoCo插件配置:
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.8</version>
<executions>
<execution>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>report</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
运行以下命令生成覆盖率报告:mvn test jacoco:report
覆盖率报告会生成在target/site/jacoco目录下,打开index.html查看详细覆盖率信息。
5. 使用IDE集成工具
如果你使用IntelliJ IDEA或Eclipse等IDE,可以直接在IDE中运行测试,并查看内置的测试报告功能:
- IntelliJ IDEA:
- 打开测试类
- 右键点击测试方法或类
- 选择"Run 'Tests in ...'"
- 在"Run"工具窗口中查看测试结果
- Eclipse:
- 打开测试类
- 右键点击测试方法或类
- 选择"Run As" -> "JUnit Test"
- 在"JUnit"视图中查看测试结果
6. 持续集成中的报告生成
如果你使用持续集成工具(如Jenkins、GitHub Actions等),通常会自动生成并展示测试报告:
- Jenkins:
- 安装JUnit插件
- 在Job配置中添加"Publish JUnit test result report"构建后操作
- 指定测试报告路径(如
target/surefire-reports/*.xml)
- GitHub Actions:
- 在Workflow文件中添加测试步骤
- 使用
actions/upload-artifact上传测试报告 - 在Actions界面查看上传的报告

浙公网安备 33010602011771号