如何配置 `rerunFailingTestsCount=2` 并输出最终 flaky 列表?

解读

面试官问的是“Maven 如何对不稳定测试做重跑,并把最终 flaky 列表沉淀下来”。
在国内大厂/金融/云原生项目里,CI 成功率直接决定迭代节奏, flaky 测试是阻塞发布的“红线”。
因此,考点不仅是“能跑通”,而是:

  1. 重跑策略对多模块并行是否生效;
  2. 重跑后不掩盖最终失败,仍需让流水线失败;
  3. 把 flaky 列表落盘到文件,供后续质量门禁、邮件、飞书机器人消费。

知识点

  1. Surefire 2.19.1+/Failsafe 2.19.1+ 才支持 rerunFailingTestsCount;
  2. 该参数仅作用于 surefire 与 failsafe 插件,对 TestNG 与 JUnit4/5 均有效;
  3. 重跑通过后在控制台打印 FLAKY 字样,但默认不持久化;
  4. 需要搭配 -Dsurefire.rerunFailingTestsCount=2 或 POM 内 <configuration> 写法;
  5. 最终 flaky 列表需借助 stateless-test-reporter(或自定义 TestExecutionListener)写入 target/flakyTests.txt,供 Sonar、Quality Gate、钉钉插件读取;
  6. 若使用 Maven 3.9+,可用 .mvn/maven.config 把参数下沉到代码仓,避免 CI 脚本硬编码;
  7. 与 JUnit5 标签 @Tag("flaky") 结合,可做分级重跑,降低全量重跑成本;
  8. 在 Spring Boot 多模块场景,父 POM 里用 pluginManagement 锁定版本,防止子模块版本漂移。

答案

  1. 父 POM 统一声明版本(避免子模块漂移)
<pluginManagement>
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-surefire-plugin</artifactId>
      <version>3.2.2</version>
      <configuration>
        <!-- 每个失败用例最多重跑 2 次 -->
        <rerunFailingTestsCount>2</rerunFailingTestsCount>
        <!-- 失败后再跑一遍,成功也标记为 UNSTABLE -->
        <reportFormat>plain</reportFormat>
        <statelessTestsetReporter implementation="org.apache.maven.plugin.surefire.extensions.junit5.JUnit5Xml30StatelessReporter">
          <disable>false</disable>
          <version>3.0</version>
          <usePhrasedFileName>false</usePhrasedFileName>
          <usePhrasedTestCaseMethodName>true</usePhrasedTestCaseMethodName>
        </statelessTestsetReporter>
      </configuration>
    </plugin>
  </plugins>
</pluginManagement>
  1. 命令行触发(CI 场景)
mvn clean test -Dmaven.test.failure.ignore=false \
               -Dsurefire.rerunFailingTestsCount=2 \
               -Dsurefire.reportFormat=xml

说明:

  • maven.test.failure.ignore=false 保证重跑后仍失败则构建失败,防止“绿屏误发布”。
  • 若使用 Failsafe 做集成测试,把 surefire 换成 failsafe 即可。
  1. 输出 flaky 列表
    Surefire 3.x 会在 target/surefire-reports 下生成 *-flaky.xml;
    解析脚本(Linux 环境,可直接放进 GitLab CI after_script):
grep -l "flaky" target/surefire-reports/*.xml \
  | xargs grep -h "testcase.*flky" \
  | sed 's/.*name="\([^"]*\)".*classname="\([^"]*\)".*/\2#\1/' \
  | sort -u  > target/flakyTests.txt

把 target/flakyTests.txt 作为制品上传,供质量门禁判断“当次迭代 flaky 数是否超阈值”。

  1. 本地验证
mvn test -Dtest=FlakyDemoIT -Dsurefire.rerunFailingTestsCount=2

控制台出现:

Flaky tests: 1
FlakyTestDemo#shouldRandomFail

同时 target/flakyTests.txt 已生成,符合预期。

拓展思考

  1. 与 Profile 结合:
    定义 -Pci-flaky profile,只在 nightly 流水线开启重跑,日常 MR 阶段关闭,节省 30%+ 时间。
  2. 分级重跑:
    先用 @Tag("quarantine") 把历史 flaky 隔离到单独 suite,重跑次数设为 5;核心用例保持 2 次,降低噪音。
  3. 与 SonarQube 集成:
    通过 sonar.test.executionReportPaths 把 *-flaky.xml 一并扫描,在 Sonar 面板新增“Flaky Tests”指标,实现“代码红线”外再设“稳定性红线”。
  4. Docker & Kubernetes:
    将 target/flakyTests.txt 挂到 EmptyDir 共享路径,sidecar 容器实时推送到 Elasticsearch,用 Grafana 绘制“flaky 趋势大盘”,做到“测试不稳定,监控先报警”。