Sub topic 14
Measuring code coverage
This chapter assumes you can already run flutter test and write unit and widget tests. You should know what test_setup covers: a test/ folder, flutter_test in dev_dependencies, and the flutter command line tool. Here you will generate a coverage report, read it, and decide what it can and cannot tell you.
What coverage measures
Code coverage records which lines of your code ran while the tests ran. A line that executed at least once is covered. A line that never executed is uncovered. The percentage is covered lines divided by instrumented lines.
Coverage answers one question: which code did no test ever execute? It does not tell you whether the tests checked anything. A test that calls a method and makes no assertion still marks every line in that method as covered.
| Coverage tells you | Coverage does not tell you |
|---|---|
| Which lines no test reached | Whether assertions are meaningful |
| Which files have no tests at all | Whether edge-case inputs were tried |
| How the number changes over time | Whether the behavior is correct |
Treat low coverage as a reliable warning and high coverage as weak evidence.
Generating the report
Flutter collects coverage with a flag on the test command:
flutter test --coverageWhen the run finishes, Flutter writes coverage/lcov.info in your project root. The file is plain text in the LCOV format. It works for unit and widget tests together, because both run under flutter test.
Each source file gets a record like this:
SF:lib/shipping.dart
DA:3,4
DA:4,4
DA:5,0
LF:3
LH:2
end_of_recordSF:is the source file path.DA:line,hitssays how many times a line executed.DA:5,0is an uncovered line.LF:is the number of instrumented lines in the file.LH:is the number of those lines that were hit.
Reading raw LCOV is tedious, so you normally convert it to a browsable report.
Viewing an HTML report
The lcov package provides genhtml. Install it with your system package manager, for example brew install lcov on macOS or sudo apt-get install lcov on Debian and Ubuntu. Then run:
flutter test --coverage
genhtml coverage/lcov.info -o coverage/html
open coverage/html/index.htmlUse xdg-open instead of open on Linux. The report lists each directory and file with its percentage. Opening a file shows the source with covered lines in one color and uncovered lines in another. The uncovered lines are the useful part, because they show where to write the next test.
Editors help too. Many Flutter extensions can read coverage/lcov.info and shade lines in the editor. The details depend on your editor, but they all read the same file.
A worked example: finding the gap
Here is a function with three branches and a test that only exercises one of them. Put both in test/shipping_test.dart to try it. In a real project the function would live in lib/.
import 'package:flutter_test/flutter_test.dart';
int shippingCents(int orderCents) {
if (orderCents <= 0) {
throw ArgumentError.value(orderCents, 'orderCents', 'must be positive');
}
if (orderCents >= 5000) {
return 0;
}
return 499;
}
void main() {
test('orders under the threshold pay flat shipping', () {
expect(shippingCents(1000), 499);
});
}The test passes, and the report shows the throw line and the return 0 line as uncovered. The report has pointed at two behaviors nobody has checked: the free-shipping rule and the input validation. Add tests for both:
import 'package:flutter_test/flutter_test.dart';
int shippingCents(int orderCents) {
if (orderCents <= 0) {
throw ArgumentError.value(orderCents, 'orderCents', 'must be positive');
}
if (orderCents >= 5000) {
return 0;
}
return 499;
}
void main() {
group('shippingCents', () {
test('orders under the threshold pay flat shipping', () {
expect(shippingCents(1000), 499);
});
test('orders at the threshold ship free', () {
expect(shippingCents(5000), 0);
});
test('non-positive orders are rejected', () {
expect(() => shippingCents(0), throwsArgumentError);
});
});
}Rerun flutter test --coverage and every line is covered. The boundary test at exactly 5000 is what makes the second test valuable. Coverage alone would have been satisfied by 6000, so choosing the inputs is still your job.
The workflow in one picture
Files that never appear
The most common surprise is that a file no test imports does not show up in the report at all. Coverage is collected from files that the test run loaded. A file with zero tests and no imports from other tested code is missing from lcov.info, so it does not drag the percentage down. A project can report 95% while a whole feature folder is untested.
A common workaround is a helper test that imports every library file, so each one is loaded and counted. Generate or maintain it as you add files:
// test/coverage_helper_test.dart
// ignore_for_file: unused_import
import 'package:my_app/shipping.dart';
import 'package:my_app/user_repository.dart';
// ...one import per file in lib/
void main() {}Replace my_app with your package name. After this change, an untested file appears with 0% instead of being hidden. This gives an honest number, and it is often lower than the one you had before.
Excluding code that should not count
Some code distorts the number without being worth testing by hand. Generated files such as *.g.dart and *.freezed.dart are the usual example. You can remove them from the report with lcov:
lcov --remove coverage/lcov.info '*.g.dart' '*.freezed.dart' \
-o coverage/lcov.infoFor individual spots in your own code, the coverage tooling understands comment markers:
void debugDump() {
// coverage:ignore-start
print('state dump');
// coverage:ignore-end
}
int fallback() => -1; // coverage:ignore-lineA file can opt out entirely with // coverage:ignore-file near the top. Use these sparingly and for a stated reason. Every ignore marker hides a line from the report, and a habit of ignoring awkward code defeats the purpose.
Computing the percentage in a script
Because lcov.info is plain text, a short awk command can total the LF: and LH: lines across all files:
awk -F: '/^LF:/{f+=$2} /^LH:/{h+=$2} END{printf "%.1f\n", h/f*100}' coverage/lcov.infoThis prints the overall line coverage, for example 87.3. You can turn it into a gate that fails when coverage drops below a minimum:
pct=$(awk -F: '/^LF:/{f+=$2} /^LH:/{h+=$2} END{printf "%.1f", h/f*100}' coverage/lcov.info)
echo "Line coverage: ${pct}%"
awk -v p="$pct" -v min=80 'BEGIN { exit (p + 0 < min + 0) }' \
|| { echo "Coverage is below 80%"; exit 1; }The final awk exits with status 1 when the percentage is below min, which makes the || branch run and stops the script with a failure code. A CI job that runs this script fails the build when coverage falls. The next chapter shows where that step fits in a pipeline.
Using coverage well
- Look at uncovered lines, not just the total. The list of misses is the actionable output.
- Watch the trend. A drop between two commits is more informative than any absolute number.
- Set a modest floor, not a perfect target. A floor such as 70 to 80 percent prevents neglect. Chasing 100 percent encourages low-value tests of trivial code.
- Weigh by risk. Business rules, parsing, and state logic deserve high coverage. Auto-generated code and thin glue code do not.
- Combine layers. Unit tests cover logic cheaply. Widget tests cover the lines that build UI. Together they reach code that neither reaches alone.
- Remember what is measured. This is line coverage. A line like
return a > b ? x : y;counts as covered even if only one side of the condition ever ran.
Common errors
- No
coverage/lcov.infoappears. You ranflutter testwithout--coverage, or the run failed before finishing. Fix failing tests first. genhtml: command not found. Thelcovpackage is not installed. Install it with your system package manager.- The percentage is suspiciously high. Untested files are missing from the report. Add the helper test that imports every file.
- Stale numbers. Old data in
coverage/can mislead you. Delete the folder, or rerun and confirm the file's modification time changed. - Generated code lowers the score. Filter it out with
lcov --remove, as shown above.
Exercise
A project reports 96% line coverage, yet a new lib/payments/ folder has no tests and the team suspects it is not counted. Why might the folder be missing from the report, what is the fix, and what will happen to the percentage afterward?
Show answer
Coverage is collected only from files that the test run loads. If no test imports anything from lib/payments/, those files never appear in coverage/lcov.info, so they do not lower the percentage. The fix is a helper test, such as test/coverage_helper_test.dart, that imports every file under lib/ (with // ignore_for_file: unused_import) and has an empty main. After that the payments files show up with 0% line coverage, and the overall percentage will drop to a more honest value.
Exercise
Write the shell command that prints overall line coverage from coverage/lcov.info, and explain which two record types it sums.
Show answer
awk -F: '/^LF:/{f+=$2} /^LH:/{h+=$2} END{printf "%.1f\n", h/f*100}' coverage/lcov.info. It sums the LF: records (lines found, meaning instrumented lines) and the LH: records (lines hit, meaning lines executed at least once) across every file, then prints hit divided by found as a percentage.