Code coverage
suggest changeCode coverage measures how much of your Dart source code is executed by your automated test suite. Dart provides built-in support for collecting VM execution traces during dart test, which can be converted to standard LCOV reports for CI integration and local HTML visualization.
Collecting Coverage with dart test
The modern Dart SDK includes coverage collection directly in the dart test runner using the --coverage flag:
dart test --coverage=coverage
This executes all tests and outputs raw VM coverage data as JSON files into the coverage/ directory.
Converting Coverage to LCOV Format
The raw JSON format produced by the Dart VM needs to be formatted into standard LCOV (lcov.info) format. Use the official coverage package:
# Activate the coverage utility globally
dart pub global activate coverage
# Format the JSON data into an LCOV report
dart pub global run coverage:format_coverage \
--lcov \
--in=coverage \
--out=coverage/lcov.info \
--packages=.dart_tool/package_config.json \
--report-on=lib
Key Options
--in: Directory containing raw coverage JSON files.--out: Destination file path for the generated LCOV file.--report-on: Directory to report coverage on (usuallylibto exclude test files and third-party code).--packages: Path to the package configuration file (.dart_tool/package_config.json).
Generating HTML Reports
Once coverage/lcov.info is generated, you can produce visual HTML reports using the genhtml utility (part of the standard lcov package on Linux/macOS, or available via Homebrew/Chocolatey):
genhtml coverage/lcov.info -o coverage/html
Open coverage/html/index.html in a web browser to inspect line-by-line coverage, highlighting uncovered branches in red and covered branches in green.
Automating with a Dart Script
You can combine these steps into a simple helper script, tool/coverage.dart:
import 'dart:io';
Future<void> main() async {
print('Running tests with coverage...');
final testResult = await Process.run(
'dart',
['test', '--coverage=coverage'],
);
stdout.write(testResult.stdout);
stderr.write(testResult.stderr);
if (testResult.exitCode != 0) {
exit(testResult.exitCode);
}
print('Formatting coverage report...');
final formatResult = await Process.run(
'dart',
[
'pub',
'global',
'run',
'coverage:format_coverage',
'--lcov',
'--in=coverage',
'--out=coverage/lcov.info',
'--packages=.dart_tool/package_config.json',
'--report-on=lib',
],
);
stdout.write(formatResult.stdout);
stderr.write(formatResult.stderr);
print('LCOV report created at coverage/lcov.info');
}
Run the script anytime with:
dart run tool/coverage.dart
Excluding Generated Files
In projects using code generation (such as json_serializable or freezed), you often want to exclude *.g.dart or *.freezed.dart from coverage metrics:
# On systems with lcov installed, remove generated files:
lcov --remove coverage/lcov.info '**/*.g.dart' '**/*.freezed.dart' -o coverage/lcov_cleaned.info