如何在GitHub Workflow中用Dart将测试结果导入Jira/Xray(Xray JSON API)
解决方案:Dart测试结果同步至Jira/Xray(Xray JSON API方式)
1. 自定义Dart脚本生成Xray兼容JSON
目前没有专门的Dart插件直接生成Xray要求的JSON格式,但可以利用Dart测试框架的回调机制,自行编写脚本捕获测试结果并组装成符合Xray API规范的JSON文件:
- 核心思路:借助
test包的测试生命周期回调(如addTestCompletionListener),收集每个测试用例的执行状态、名称、耗时等信息,再映射为Xray API要求的结构(包含info和tests两个核心部分)。 - 示例代码片段:
import 'package:test/test.dart'; import 'dart:convert'; import 'dart:io'; final List<Map<String, dynamic>> _testResults = []; void main() { // 监听测试完成事件,收集结果 setUpAll(() { addTestCompletionListener((testInfo) { final status = testInfo.result.resultType == ResultType.success ? 'PASS' : testInfo.result.resultType == ResultType.skip ? 'SKIP' : 'FAIL'; _testResults.add({ "testKey": "PROJ-456", // 替换为Jira中对应测试用例的Key,可通过注解/映射表动态获取 "status": status, "comment": testInfo.result.message ?? "No additional info", "duration": testInfo.time.elapsed.inMilliseconds }); }); }); // 你的测试用例 test('加法测试', () { expect(1 + 1, equals(2)); }); test('失败测试示例', () { expect(1 + 1, equals(3)); }); // 测试全部完成后生成Xray JSON文件 tearDownAll(() { final xrayPayload = jsonEncode({ "info": { "summary": "Dart测试执行结果(GitHub Workflow)", "description": "自动同步的测试报告", "project": "PROJ", // 你的Jira项目Key "version": "1.0.0" // 可选,对应项目版本 }, "tests": _testResults }); File('xray-test-results.json').writeAsStringSync(xrayPayload); }); } - GitHub Workflow集成:在Workflow中先运行测试生成JSON,再通过
curl调用Xray API上传:jobs: sync-test-results: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: dart-lang/setup-dart@v1 - run: dart pub get - run: dart test test/your_test_file.dart # 执行测试并生成xray-test-results.json - name: 上传至Xray run: | curl -X POST "https://your-jira-domain/rest/raven/1.0/import/execution" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer ${{ secrets.XRAY_API_TOKEN }}" \ -d @xray-test-results.json
2. 转换JUnit报告为Xray JSON
如果你已经能生成JUnit格式的测试报告,可以在GitHub Workflow中添加转换步骤,将JUnit XML转为Xray兼容的JSON:
- 操作步骤:
- 生成JUnit报告:
dart test --reporter junit > test-results.xml - 转换格式:用Node.js/Python编写简单脚本读取XML,提取测试结果并映射为Xray JSON结构;或用轻量转换工具实现格式适配。
- 调用Xray API上传转换后的JSON文件。
- 生成JUnit报告:
关键注意事项
- 测试用例Key映射:确保Dart测试用例与Jira/Xray中的测试用例Key一一对应,可通过在测试注解中添加Key(如
// testKey: PROJ-456),再在自定义脚本中解析获取,或维护一个映射表。 - Xray API认证:根据你的Xray配置选择认证方式,支持Bearer Token、基本认证(用户名+API Token)等,认证信息建议存在GitHub Secrets中,避免硬编码。
- Xray JSON规范:严格遵循Xray API的格式要求,比如
status字段可选值为PASS/FAIL/SKIP/TODO等,info部分的字段需匹配Jira项目配置。
内容的提问来源于stack exchange,提问作者shilpa vania
相关产品推荐
相关产品推荐

