CodeBlanks Logo Icon CodeBlanks

Coverage

Learn test coverage measurement.

Coverage

Coverage measures how much of the code your tests exercise. dart test --coverage=coverage produces an LCOV report; genhtml turns it into HTML.

Two types: line coverage (number of executed lines) and branch coverage (how many if/else branches were taken). 100% line does not mean 100% branch.

Coverage is an indicator of test quality but not sufficient alone. Even with high coverage edge cases may be untested. Coverage shows the picture; it does not guarantee quality.

Line vs branch coverage

Line coverage gives the ratio of executed source lines. An if line counts as 'executed' whether the condition is true or false.

Branch coverage tests both arms of an if. For if (x) { a(); } else { b(); } both a() and b() must be called.

Therefore branch coverage is stricter. You can have 90% line coverage but only 60% branch coverage. Both should be tracked.

Practice Define a CoverageReport

Define a CoverageReport class with final int covered; final int total; CoverageReport(this.covered, this.total); double get percent => total == 0 ? 0 : (covered / total) * 100;. In main create final report = CoverageReport(85, 100); and add print('${report.percent.toStringAsFixed(0)}%');.

Starter code

main.dart
void main() {
  // define a CoverageReport class (covered, total fields; percent getter)
  // create a report; print percent as a percentage
}

Sample solution

main.dart
class CoverageReport {
  final int covered;
  final int total;
  CoverageReport(this.covered, this.total);
  double get percent => total == 0 ? 0 : (covered / total) * 100;
}

void main() {
  final report = CoverageReport(85, 100);
  print('${report.percent.toStringAsFixed(0)}%');
}

Expected output

85%

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does dart test --coverage produce?

  • LCOV/coverage data Correct answer
  • An executable
  • An HTML report
  • A test file

Explanation: dart test --coverage produces LCOV-format data.

2 Match the coverage parts

Term Meaning
--coverage Flag
lcov.info Data file
genhtml HTML generator
100% Full coverage

3 Coverage ratio

Question
var lineCoverage = ____;
Answer
var lineCoverage = 0.85;

Explanation: coverage is a ratio between 0 and 1.

All lessons in Expert