如何合并两次Cucumber HTML测试报告并展示最终用例执行结果?
Got it, let's tackle this problem of merging two Cucumber HTML reports (from initial run and rerun) to show the final test results—where scenarios that failed first but passed on rerun show as "passed" in the final report. Here are two reliable approaches:
方法一:用JSON报告+自定义脚本合并(灵活可控)
Cucumber HTML reports are static, so merging them directly is tricky. Instead, we'll work with JSON reports (structured data) to merge results, then generate a final HTML report from the merged JSON.
生成两次运行的JSON报告
- 首次运行:捕获失败用例并生成JSON报告
cucumber --format json --out report_first_run.json --format rerun --out failed_scenarios.txt - 重跑失败用例:仅针对失败场景生成第二份JSON报告
cucumber @failed_scenarios.txt --format json --out report_rerun.json
- 首次运行:捕获失败用例并生成JSON报告
用自定义脚本合并JSON报告
核心逻辑是:重跑结果优先覆盖首次运行结果。比如,如果某个场景在两份报告中都存在,我们就采用重跑后的状态。这里提供一个简单的Python脚本实现(你也可以改成Ruby/JS版本):
import json # 加载两份报告 with open('report_first_run.json', 'r') as f: initial_report = json.load(f) with open('report_rerun.json', 'r') as f: rerun_report = json.load(f) # 构建重跑场景的ID映射表 rerun_scenario_map = {} for feature in rerun_report: for scenario in feature.get('elements', []): scenario_id = scenario['id'] rerun_scenario_map[scenario_id] = scenario # 合并报告:替换首次运行中已重跑的场景 for feature in initial_report: updated_scenarios = [] for scenario in feature.get('elements', []): if scenario['id'] in rerun_scenario_map: # 用重跑后的场景结果替换 updated_scenarios.append(rerun_scenario_map[scenario['id']]) else: # 保留首次运行的结果 updated_scenarios.append(scenario) feature['elements'] = updated_scenarios # 保存合并后的JSON文件 with open('merged_report.json', 'w') as f: json.dump(initial_report, f, indent=2)从合并后的JSON生成最终HTML报告
用cucumber-html-reporter这个Node.js工具把合并后的JSON转换成易读的HTML报告:- 先安装工具:
npm install cucumber-html-reporter --save-dev - 创建
generate_final_report.js文件:const reporter = require('cucumber-html-reporter'); const options = { theme: 'bootstrap', jsonFile: 'merged_report.json', output: 'final_report.html', reportSuiteAsScenarios: true, launchReport: false, metadata: { "App Version": "1.0.0", "Test Environment": "UAT", "Browser": "Chrome 118.0", "Platform": "Windows 10", "Executed": "Rerun Merged" } }; reporter.generate(options); - 运行脚本生成最终报告:
node generate_final_report.js
- 先安装工具:
方法二:用第三方工具快速合并
如果不想写自定义代码,可以用cucumber-report-merger工具自动处理JSON合并:
安装工具
npm install -g cucumber-report-merger合并JSON报告
cucumber-report-merger -i report_first_run.json report_rerun.json -o merged_report.json生成最终HTML报告
和方法一的第三步一样,用cucumber-html-reporter把合并后的JSON转换成HTML报告即可。
关键注意点
- 一定要用JSON报告来合并:HTML是静态页面,不适合程序化修改;JSON是结构化数据,更容易处理结果覆盖逻辑。
- 合并后的报告会自动将“首次失败、重跑通过”的场景标记为通过,完美呈现最终测试结果。
- 你可以修改HTML报告生成脚本里的metadata,添加应用版本、测试环境等信息,方便干系人理解报告背景。
内容的提问来源于stack exchange,提问作者Richlewis

