dart-collect-coverage

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Implementing Dart and Flutter Test Coverage

Dart与Flutter测试覆盖率实现指南

Contents

目录

Testing Fundamentals

测试基础

Structure your test suites using the standard Dart testing paradigms. Use
package:test
for Dart projects and
flutter_test
for Flutter projects.
  • Unit Tests: Verify individual functions, methods, or classes.
  • Component/Widget Tests: Verify component behavior, layout, and interaction using mock objects (
    package:mockito
    ).
  • Integration Tests: Verify entire app flows on simulated or real devices.
使用标准Dart测试范式构建你的测试套件。Dart项目使用
package:test
,Flutter项目使用
flutter_test
  • 单元测试: 验证单个函数、方法或类。
  • 组件/Widget测试: 使用模拟对象(
    package:mockito
    )验证组件的行为、布局和交互。
  • 集成测试: 在模拟设备或真实设备上验证整个应用流程。

Coverage Directives

覆盖率指令

Exclude specific lines, blocks, or entire files from coverage metrics using inline comments. Pass the
--check-ignore
flag during formatting to enforce these directives.
  • Ignore a single line:
    // coverage:ignore-line
  • Ignore a block of code:
    // coverage:ignore-start
    and
    // coverage:ignore-end
  • Ignore an entire file:
    // coverage:ignore-file
使用行内注释将特定代码行、代码块或整个文件排除在覆盖率统计之外。格式化时传入
--check-ignore
参数以强制执行这些指令。
  • 忽略单行代码:
    // coverage:ignore-line
  • 忽略代码块:
    // coverage:ignore-start
    // coverage:ignore-end
  • 忽略整个文件:
    // coverage:ignore-file

Workflow: Configuring and Generating Coverage Reports

工作流:配置并生成覆盖率报告

Follow this sequential workflow to add the coverage package, execute tests, and generate an LCOV report.
Task Progress Checklist:
  • 1. Add
    coverage
    as a
    dev_dependency
    .
  • 2. Execute the automated coverage script.
  • 3. Validate the LCOV output.
按照以下顺序工作流添加coverage包、执行测试并生成LCOV报告。
任务进度清单:
  • 1. 将
    coverage
    添加为
    dev_dependency
  • 2. 执行自动化覆盖率脚本。
  • 3. 验证LCOV输出结果。

1. Add Dependencies

1. 添加依赖

Add the
coverage
package as a
dev_dependency
to your project. Do not add it to standard dependencies.
If working in a standard Dart project:
bash
dart pub add dev:coverage
If working in a Flutter project:
bash
flutter pub add dev:coverage
coverage
包作为
dev_dependency
添加到你的项目中。不要将其添加到标准依赖项里。
如果是标准Dart项目:
bash
dart pub add dev:coverage
如果是Flutter项目:
bash
flutter pub add dev:coverage

2. Collect Coverage and Generate LCOV

2. 收集覆盖率并生成LCOV报告

Use the bundled
test_with_coverage
script. This script automatically runs all tests, collects the JSON coverage data from the Dart VM, and formats it into an LCOV report.
bash
dart run coverage:test_with_coverage
Note: If working within a Dart workspace (monorepo), specify the test directories explicitly (e.g.,
dart run coverage:test_with_coverage -- pkgs/foo/test pkgs/bar/test
).
使用内置的
test_with_coverage
脚本。该脚本会自动运行所有测试,从Dart VM收集JSON格式的覆盖率数据,并将其格式化为LCOV报告。
bash
dart run coverage:test_with_coverage
注意:如果在Dart工作区(单体仓库)中工作,请明确指定测试目录(例如:
dart run coverage:test_with_coverage -- pkgs/foo/test pkgs/bar/test
)。

3. Feedback Loop: Validate Output

3. 反馈循环:验证输出

Run validator -> review errors -> fix:
  1. Verify that the
    coverage/
    directory was created in the project root.
  2. Ensure
    coverage/coverage.json
    (raw data) and
    coverage/lcov.info
    (formatted report) exist.
  3. If coverage is missing for specific files, ensure they are imported and executed by your test files, or add
    // coverage:ignore-file
    if they are intentionally excluded.
运行验证器 → 查看错误 → 修复:
  1. 确认项目根目录下已创建
    coverage/
    文件夹。
  2. 确保
    coverage/coverage.json
    (原始数据)和
    coverage/lcov.info
    (格式化报告)已存在。
  3. 如果特定文件的覆盖率缺失,请确保它们已被测试文件导入并执行;如果是有意排除的文件,请添加
    // coverage:ignore-file
    注释。

Workflow: Advanced Manual Coverage Collection

工作流:高级手动覆盖率收集

If you require granular control over the VM service, isolate pausing, or need branch/function-level coverage, use the manual collection workflow.
Task Progress Checklist:
  • 1. Run tests with VM service enabled.
  • 2. Collect raw JSON coverage.
  • 3. Format JSON to LCOV.
如果你需要对VM服务、隔离线程暂停进行精细控制,或者需要分支/函数级别的覆盖率数据,请使用手动收集工作流。
任务进度清单:
  • 1. 启用VM服务运行测试。
  • 2. 收集原始JSON格式覆盖率数据。
  • 3. 将JSON格式转换为LCOV格式。

1. Run Tests with VM Service

1. 启用VM服务运行测试

Execute tests while pausing isolates on exit and exposing the VM service on a specific port (e.g., 8181).
bash
dart run --pause-isolates-on-exit --disable-service-auth-codes --enable-vm-service=8181 test &
在退出时暂停隔离线程,并在指定端口(例如8181)暴露VM服务的情况下执行测试。
bash
dart run --pause-isolates-on-exit --disable-service-auth-codes --enable-vm-service=8181 test &

2. Collect Raw Coverage

2. 收集原始覆盖率数据

Extract the coverage data from the running VM service and output it to a JSON file.
bash
dart run coverage:collect_coverage --wait-paused --uri=http://127.0.0.1:8181/ -o coverage/coverage.json --resume-isolates
Optional: Append
--function-coverage
and
--branch-coverage
to gather deeper metrics (requires Dart VM 2.17.0+).
从运行中的VM服务提取覆盖率数据并输出到JSON文件。
bash
dart run coverage:collect_coverage --wait-paused --uri=http://127.0.0.1:8181/ -o coverage/coverage.json --resume-isolates
可选:添加
--function-coverage
--branch-coverage
参数以收集更详细的指标(需要Dart VM 2.17.0及以上版本)。

3. Format to LCOV

3. 转换为LCOV格式

Convert the raw JSON data into the standard LCOV format.
bash
dart run coverage:format_coverage --packages=.dart_tool/package_config.json --lcov -i coverage/coverage.json -o coverage/lcov.info --check-ignore
将原始JSON数据转换为标准LCOV格式。
bash
dart run coverage:format_coverage --packages=.dart_tool/package_config.json --lcov -i coverage/coverage.json -o coverage/lcov.info --check-ignore

Examples

示例

Example:
pubspec.yaml
Configuration

示例:
pubspec.yaml
配置

Ensure your
pubspec.yaml
reflects the
coverage
package strictly under
dev_dependencies
.
yaml
name: my_dart_app
environment:
  sdk: ^3.0.0

dependencies:
  path: ^1.8.0

dev_dependencies:
  test: ^1.24.0
  coverage: ^1.15.0
确保你的
pubspec.yaml
文件中
coverage
包严格位于
dev_dependencies
下。
yaml
name: my_dart_app
environment:
  sdk: ^3.0.0

dependencies:
  path: ^1.8.0

dev_dependencies:
  test: ^1.24.0
  coverage: ^1.15.0

Example: Applying Ignore Directives

示例:应用忽略指令

Use ignore directives to prevent generated code or untestable edge cases from lowering coverage scores.
dart
// coverage:ignore-file
import 'package:meta/meta.dart';

class SystemConfig {
  final String env;

  SystemConfig(this.env);

  // coverage:ignore-start
  void legacyInit() {
    print('Deprecated initialization');
  }
  // coverage:ignore-end

  bool isProduction() {
    if (env == 'prod') return true;
    return false; // coverage:ignore-line
  }
}
使用忽略指令防止生成的代码或无法测试的边缘情况拉低覆盖率分数。
dart
// coverage:ignore-file
import 'package:meta/meta.dart';

class SystemConfig {
  final String env;

  SystemConfig(this.env);

  // coverage:ignore-start
  void legacyInit() {
    print('Deprecated initialization');
  }
  // coverage:ignore-end

  bool isProduction() {
    if (env == 'prod') return true;
    return false; // coverage:ignore-line
  }
}