O. BERHILI
Flutter · Testing · CI/CD5 min read

Flutter test coverage: an 80% gate on GitLab CI

An 80% Flutter coverage gate on GitLab CI: count untested files, strip generated code from lcov, fail the job, annotate MR diffs, test notifiers first.

On this page

On my current Flutter project we enforce an 80% line coverage gate in GitLab CI. The job runs flutter test --coverage, strips generated code from lcov.info, computes the percentage and fails below 80. GitLab picks up the number for the merge request widget, and a Cobertura report marks covered and uncovered lines in the diff. Wiring it up takes an afternoon. Keeping the team from gaming it takes a few rules about what counts and what to test first.

What lcov.info gets wrong by default

A coverage number is only useful if it measures code people wrote and reviewed. In a typical Flutter app, the raw lcov.info has three problems:

  • Generated code is counted. *.g.dart from json_serializable, *.freezed.dart and the localization classes from flutter gen-l10n can add thousands of lines. Depending on what the tests touch, they push the score up or down, and nobody can act on either.
  • Untested files are invisible. flutter test --coverage only reports files that some test loaded. A new feature folder with zero tests does not lower the number, because it is simply absent. This is the most common way coverage lies, and nobody has to cheat for it to happen.
  • Bootstrap code is counted. main.dart, firebase_options.dart and dependency wiring are exercised by integration tests or not at all. I exclude them explicitly and keep that list short.

Step 1: make untested files show up

For the invisible files, CI generates a test that imports every hand-written file under lib/. Files nobody tests then show up at 0% instead of disappearing.

bash
#!/usr/bin/env bash
# tool/coverage_helper.sh: run before `flutter test --coverage`
set -eu
PACKAGE=$(grep -m1 '^name:' pubspec.yaml | awk '{print $2}')

{
  echo "// GENERATED IN CI. Do not commit."
  echo "// ignore_for_file: unused_import"
  find lib -name '*.dart' ! -name '*.g.dart' ! -name '*.freezed.dart' \
    | xargs grep -L '^part of' \
    | sed "s|^lib/\(.*\)|import 'package:$PACKAGE/\1';|"
  echo "void main() {}"
} > test/coverage_helper_test.dart

grep -L '^part of' skips part files, which cannot be imported on their own. If some files only compile on one platform (conditional imports, dart:html), exclude them here as well. The generated helper goes in .gitignore.

Step 2: clean the report and enforce the threshold

lcov --remove coverage/lcov.info '*.g.dart' '*.freezed.dart' -o coverage/lcov.cleaned.info works, but then lcov has to be installed in the Flutter image, and lcov 2.x fails on patterns that match nothing unless you pass --ignore-errors unused. I use a small Dart script with no dependencies instead. It runs wherever Flutter runs, and the exclusion list lives in the repository, where reviewers see it change.

dart
// tool/coverage_gate.dart
import 'dart:io';

final excluded = [
  RegExp(r'\.g\.dart$'),
  RegExp(r'\.freezed\.dart$'),
  RegExp(r'/l10n/'),
  RegExp(r'lib/main\.dart$'),
  RegExp(r'firebase_options\.dart$'),
];

void main(List<String> args) {
  final minimum = args.isEmpty ? 80.0 : double.parse(args.first);
  final cleaned = StringBuffer();
  var found = 0, hit = 0;
  var skip = false;
  for (final line in File('coverage/lcov.info').readAsLinesSync()) {
    if (line.startsWith('SF:')) {
      skip = excluded.any((pattern) => pattern.hasMatch(line.substring(3)));
    }
    if (skip) continue;
    cleaned.writeln(line);
    if (line.startsWith('DA:')) {
      found++;
      if (int.parse(line.substring(3).split(',')[1]) > 0) hit++;
    }
  }
  File('coverage/lcov.cleaned.info').writeAsStringSync(cleaned.toString());
  final percent = found == 0 ? 0.0 : hit * 100 / found;
  print('Coverage: ${percent.toStringAsFixed(2)}% ($hit/$found lines)');
  if (percent < minimum) {
    stderr.writeln('Coverage is below the $minimum% gate.');
    exit(1);
  }
}

Besides writing the cleaned report for the next job, the script prints a single line in a fixed format and exits with code 1 under the threshold. The threshold is passed as an argument, so changing it shows up as a CI change instead of an edit buried in a script.

Step 3: wire it into GitLab CI

yaml
stages: [test, report]

variables:
  PUB_CACHE: "$CI_PROJECT_DIR/.pub-cache"
  MIN_COVERAGE: "80"

unit_tests:
  stage: test
  image: ghcr.io/cirruslabs/flutter:stable # pin the exact version your team uses
  cache:
    key: { files: [pubspec.lock] }
    paths: [.pub-cache/]
  script:
    - flutter pub get
    - dart run build_runner build --delete-conflicting-outputs
    - bash tool/coverage_helper.sh
    - flutter test --coverage
    - dart run tool/coverage_gate.dart "$MIN_COVERAGE"
  coverage: '/Coverage: \d+\.\d+%/'
  artifacts:
    when: always
    paths: [coverage/lcov.cleaned.info]

coverage_report:
  stage: report
  image: python:3.12-slim
  when: always # annotate the MR even when the gate fails
  script:
    - pip install --quiet lcov_cobertura
    - lcov_cobertura coverage/lcov.cleaned.info --output coverage/cobertura.xml
  artifacts:
    reports:
      coverage_report:
        coverage_format: cobertura
        path: coverage/cobertura.xml

A few details in that file:

  • PUB_CACHE points inside the project directory because GitLab only caches paths under it. With the cache keyed on pubspec.lock, it is rebuilt only when dependencies change.
  • GitLab applies the coverage: regex to the job log, shows the value in the merge request widget and charts it over time in repository analytics.
  • Once the pipeline finishes, the Cobertura artifact drives line-level annotations in the merge request diff. Reviewers see which new lines no test touched, which is often more useful than the global number.
  • The report job runs on a slim Python image because lcov_cobertura is a Python tool. It gets the cleaned report as an artifact from the previous stage, and the Flutter image stays untouched.
  • If generated files are committed, drop the build_runner step. If they are not, it has to run before the tests or the code will not compile.

Rules that keep the number honest

Without a few rules, a coverage gate turns into a game. These are the ones I hold to:

  • tool/coverage_gate.dart and .gitlab-ci.yml go under CODEOWNERS, with Code Owner approval if your GitLab tier has it. Excluding a folder to get green is the classic cheat, so the exclusion list needs an owner.
  • I treat ignore comments like lint suppressions. package:coverage honors // coverage:ignore-line and // coverage:ignore-start / ignore-end. They are fine for genuine platform glue, and each one needs a reason in review.
  • I reject tests without assertions. A test that calls a method and checks nothing raises coverage and protects nothing.
  • I read the diff annotations as well as the number. A merge request can keep the project at 82% while its own new code is barely tested.
  • On legacy code I ratchet: the gate starts at today's number, goes up as coverage climbs, and never comes down. On a greenfield app I set it early, while it is still cheap.

Test the domain and notifiers first

The fastest honest coverage comes from layers where bugs are expensive and tests are cheap. In an app layered as clean architecture I go in this order:

  1. Domain: entities, value objects, validation, use cases and DTO mapping. Pure Dart, fast, no mocks. Parsing edge cases (missing field, null, unknown enum value) catch real production bugs.
  2. Notifiers: every state transition, including loading, empty, error, retry and last page reached. With Riverpod this is a ProviderContainer.test with overrides, no widget tree needed.
  3. Repositories: cache and offline fallback logic, against fake data sources.
  4. Widgets with behavior: form validation, error and empty states, layouts where RTL direction matters.

Notifiers come early because many UI bugs start there: a spinner that never stops, an error state that hides stale data, a retry that fires twice. Tested without a widget tree, they run fast and rarely flake. A notifier test on an illustrative listing form:

dart
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';

void main() {
  late FakeListingsRepository repository;
  late ProviderContainer container;

  setUp(() {
    repository = FakeListingsRepository();
    // Riverpod 3: disposed automatically when the test ends.
    container = ProviderContainer.test(overrides: [
      listingsRepositoryProvider.overrideWithValue(repository),
    ]);
  });

  test('rejects a negative price without calling the API', () async {
    final notifier = container.read(listingDraftProvider.notifier);

    notifier.setPrice('-1200');
    final submitted = await notifier.submit();

    expect(submitted, isFalse);
    expect(container.read(listingDraftProvider).priceError, PriceError.negative);
    expect(repository.createdListings, isEmpty);
  });
}

What I leave for later: widget tests for trivial layout, like a Column with a title and an icon. They break on every design tweak and prove little.

Why 80% and not 100%

At 100%, every getter, constant, layout widget and line of platform glue needs a test. The team learns to write tests that please the tool, and ignore comments multiply until the number means nothing. The last stretch to 100% also costs more than everything before it and catches fewer bugs.

80% is high enough that an untested feature visibly pulls the number down (thanks to the helper from step 1), and low enough that nobody has to fake a test to merge a legitimate change. Coverage only proves that code ran. Checking the assertions is the reviewer's job, and the gate is a floor.

I would not add a gate to a prototype, a short-lived spike, or a team that has not agreed on how it tests. A gate records an agreement the team already has.

Setup checklist

  • flutter test --coverage runs in CI on every merge request.
  • A generated helper test imports all of lib/, so untested files count as 0%.
  • *.g.dart, *.freezed.dart, l10n and bootstrap files are stripped before the number is computed.
  • The job fails below the threshold and prints a line GitLab's coverage: regex can parse.
  • A Cobertura coverage_report artifact shows uncovered lines in the merge request diff.
  • .pub-cache is cached with a key on pubspec.lock.
  • The exclusion list and threshold sit under CODEOWNERS, and the threshold only goes up.
01

If you need this on your app

Open to roles & contracts

Need a senior mobile developer?

I join teams as a senior Flutter or iOS developer, or take on contract work, from architecture and CI to store releases.