You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置Maven任务:测试失败触发报错且生成HTML测试报告?

解决Maven同时生成测试报告并在测试失败时返回错误码的问题

有两种可靠的方式满足你的需求:

方式一:使用命令行参数直接实现

无需修改pom.xml,执行以下命令即可:

mvn test surefire-report:report-only site --fail-at-end
  • test:执行所有单元测试,失败时标记构建为失败但不立即终止
  • surefire-report:report-only:直接读取target/surefire-reports目录下的测试结果生成HTML报告,不会重复执行测试
  • site:将生成的测试报告整合到Maven站点中(如果不需要站点,可省略此部分,只保留test surefire-report:report-only --fail-at-end)
  • --fail-at-end:让Maven在所有任务执行完成后,再根据之前的测试失败情况返回非0退出码

方式二:通过pom.xml配置实现(适合长期复用)

在项目的pom.xml中添加以下插件配置,后续只需执行mvn site --fail-at-end即可:

<build>
  <plugins>
    <!-- 配置Site插件在执行前先跑测试 -->
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-site-plugin</artifactId>
      <version>3.12.1</version>
      <executions>
        <execution>
          <phase>site</phase>
          <goals>
            <goal>site</goal>
          </goals>
          <configuration>
            <preSiteHook>test</preSiteHook>
          </configuration>
        </execution>
      </executions>
    </plugin>
    <!-- 配置Surefire报告插件在Site阶段生成报告 -->
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-surefire-report-plugin</artifactId>
      <version>3.2.5</version>
      <executions>
        <execution>
          <phase>site</phase>
          <goals>
            <goal>report-only</goal>
          </goals>
        </execution>
      </executions>
    </plugin>
  </plugins>
</build>

执行命令:

mvn site --fail-at-end

该配置会让Site阶段自动先执行测试,生成报告后再根据测试结果返回对应退出码。

为什么之前的命令无效?

  • mvn surefire-report:report site:surefire-report:report会自动执行测试,但插件本身不会将测试失败标记为构建失败,所以无论结果如何Maven都返回成功
  • mvn test surefire-report:report site:surefire-report:report会重新触发测试阶段,且默认测试失败后直接终止构建,即使加--fail-at-end也会因为重复执行测试导致逻辑混乱,改用report-only即可避免这个问题

内容的提问来源于stack exchange,提问作者gad_gadskiy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 03:24:22