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

如何让Dart或Flutter单元测试自动重复执行N次并报告结果?

实现Flutter单元测试重复执行N次并在失败时生成报告

方法一:Shell脚本(适用于Mac/Linux)

编写可执行脚本,循环指定次数执行测试,一旦失败就生成报告并终止循环:

#!/bin/bash
N=10  # 替换为你需要的重复次数
REPORT_FILE="test_failure_report.txt"

for ((i=1; i<=N; i++))
do
  echo "=== 开始第 $i 轮测试 ==="
  flutter test --machine > test_output.json
  if [ $? -ne 0 ]; then
    echo "=== 第 $i 轮测试失败,生成报告 ==="
    grep -A 20 '"status":"failed"' test_output.json >> $REPORT_FILE
    echo "=== 测试失败,终止循环 ==="
    exit 1
  fi
done
echo "=== 所有 $N 轮测试全部通过 ==="

使用步骤:

  • 将代码保存为repeat_test.sh
  • 执行chmod +x repeat_test.sh赋予执行权限
  • 运行./repeat_test.sh

方法二:Windows批处理脚本

针对Windows环境,编写批处理文件实现相同逻辑:

@echo off
set N=10  # 设置重复次数
set REPORT_FILE=test_failure_report.txt

for /l %%i in (1,1,%N%) do (
  echo === 开始第 %%i 轮测试 ===
  flutter test --machine > test_output.json
  if errorlevel 1 (
    echo === 第 %%i 轮测试失败,生成报告 ===
    findstr /A:C /N "failed" test_output.json >> %REPORT_FILE%
    echo === 测试失败,终止循环 ===
    exit /b 1
  )
)
echo === 所有 %N% 轮测试全部通过 ===

使用步骤:

  • 保存为repeat_test.bat
  • 双击文件或在命令行中执行repeat_test.bat

方法三:Dart脚本(跨平台)

用Dart编写脚本,无需考虑系统差异:

import 'dart:io';

void main() async {
  const int repeatTimes = 10; // 设定重复次数
  const String reportPath = 'test_failure_report.txt';

  for (int i = 1; i <= repeatTimes; i++) {
    print('=== 开始第 $i 轮测试 ===');
    final process = await Process.start('flutter', ['test', '--machine']);
    
    final output = await process.stdout.transform(SystemEncoding.decoder).join();
    await process.stderr.transform(SystemEncoding.decoder).join();
    final exitCode = await process.exitCode;

    if (exitCode != 0) {
      print('=== 第 $i 轮测试失败,生成报告 ===');
      final reportFile = File(reportPath);
      await reportFile.writeAsString('=== 第 $i 轮测试失败详情 ===\n$output\n\n', mode: FileMode.append);
      print('=== 测试失败,终止循环 ===');
      exit(1);
    }
  }
  print('=== 所有 $repeatTimes 轮测试全部通过 ===');
}

使用步骤:

  • 保存为repeat_test.dart
  • 运行dart run repeat_test.dart

关于测试报告

  • 使用flutter test --machine参数可生成JSON格式的机器可读输出,方便精准提取失败用例的信息
  • 上述脚本中,失败时会将关键错误信息写入指定报告文件,你可以根据需求调整解析逻辑,比如提取失败用例名称、错误堆栈等

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 23:50:23