快速生成单元测试报告

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插件生成代码覆盖率报告:

  1. 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:
    1. 打开测试类
    2. 右键点击测试方法或类
    3. 选择"Run 'Tests in ...'"
    4. 在"Run"工具窗口中查看测试结果
  • Eclipse:
    1. 打开测试类
    2. 右键点击测试方法或类
    3. 选择"Run As" -> "JUnit Test"
    4. 在"JUnit"视图中查看测试结果

6. 持续集成中的报告生成

如果你使用持续集成工具(如Jenkins、GitHub Actions等),通常会自动生成并展示测试报告:

  • Jenkins:
    1. 安装JUnit插件
    2. 在Job配置中添加"Publish JUnit test result report"构建后操作
    3. 指定测试报告路径(如target/surefire-reports/*.xml
  • GitHub Actions:
    1. 在Workflow文件中添加测试步骤
    2. 使用actions/upload-artifact上传测试报告
    3. 在Actions界面查看上传的报告
posted @ 2025-03-24 16:26  ni当像鸟飞往你的山  阅读(144)  评论(0)    收藏  举报