如何配置 `rerunFailingTestsCount=2` 并输出最终 flaky 列表?
解读
面试官问的是“Maven 如何对不稳定测试做重跑,并把最终 flaky 列表沉淀下来”。
在国内大厂/金融/云原生项目里,CI 成功率直接决定迭代节奏, flaky 测试是阻塞发布的“红线”。
因此,考点不仅是“能跑通”,而是:
- 重跑策略对多模块并行是否生效;
- 重跑后不掩盖最终失败,仍需让流水线失败;
- 把 flaky 列表落盘到文件,供后续质量门禁、邮件、飞书机器人消费。
知识点
- Surefire 2.19.1+/Failsafe 2.19.1+ 才支持
rerunFailingTestsCount; - 该参数仅作用于 surefire 与 failsafe 插件,对 TestNG 与 JUnit4/5 均有效;
- 重跑通过后在控制台打印
FLAKY字样,但默认不持久化; - 需要搭配
-Dsurefire.rerunFailingTestsCount=2或 POM 内<configuration>写法; - 最终 flaky 列表需借助 stateless-test-reporter(或自定义
TestExecutionListener)写入target/flakyTests.txt,供 Sonar、Quality Gate、钉钉插件读取; - 若使用 Maven 3.9+,可用
.mvn/maven.config把参数下沉到代码仓,避免 CI 脚本硬编码; - 与 JUnit5 标签
@Tag("flaky")结合,可做分级重跑,降低全量重跑成本; - 在 Spring Boot 多模块场景,父 POM 里用
pluginManagement锁定版本,防止子模块版本漂移。
答案
- 父 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>
- 命令行触发(CI 场景)
mvn clean test -Dmaven.test.failure.ignore=false \
-Dsurefire.rerunFailingTestsCount=2 \
-Dsurefire.reportFormat=xml
说明:
maven.test.failure.ignore=false保证重跑后仍失败则构建失败,防止“绿屏误发布”。- 若使用 Failsafe 做集成测试,把
surefire换成failsafe即可。
- 输出 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 数是否超阈值”。
- 本地验证
mvn test -Dtest=FlakyDemoIT -Dsurefire.rerunFailingTestsCount=2
控制台出现:
Flaky tests: 1
FlakyTestDemo#shouldRandomFail
同时 target/flakyTests.txt 已生成,符合预期。
拓展思考
- 与 Profile 结合:
定义-Pci-flakyprofile,只在 nightly 流水线开启重跑,日常 MR 阶段关闭,节省 30%+ 时间。 - 分级重跑:
先用@Tag("quarantine")把历史 flaky 隔离到单独 suite,重跑次数设为 5;核心用例保持 2 次,降低噪音。 - 与 SonarQube 集成:
通过sonar.test.executionReportPaths把*-flaky.xml一并扫描,在 Sonar 面板新增“Flaky Tests”指标,实现“代码红线”外再设“稳定性红线”。 - Docker & Kubernetes:
将target/flakyTests.txt挂到 EmptyDir 共享路径,sidecar 容器实时推送到 Elasticsearch,用 Grafana 绘制“flaky 趋势大盘”,做到“测试不稳定,监控先报警”。