Sub topic 15
Running the suite in continuous integration
Continuous integration (CI) runs your checks on a clean machine every time code is pushed or a pull request opens. Tests that only run on your laptop get skipped and slowly break. This chapter turns the commands from earlier chapters into an automated pipeline, and covers what usually goes wrong when you do.
This chapter assumes you can already:
- write unit, widget and golden tests;
- run
flutter testandflutter test --coveragelocally; - read a basic YAML file;
- use Git and a hosted repository such as GitHub.
The examples use GitHub Actions. The same ideas apply to GitLab CI, Bitrise, Codemagic and other services. Only the file syntax changes.
What a CI run should do
A good pipeline fails fast and cheaply first, then spends time on slower checks. For a Flutter app, the usual order is:
- Check out the code and install a pinned Flutter SDK.
- Download dependencies with
flutter pub get. - Check formatting and run static analysis.
- Run unit, widget and golden tests with coverage.
- Enforce a coverage threshold and publish the report.
- Run integration tests on an emulator, usually as a separate job.
The key point is that every step is a command with an exit code. CI treats a non-zero exit code as failure. flutter test exits non-zero when any test fails, so you rarely need special handling.
A first workflow
Create .github/workflows/ci.yml in your repository:
name: CI
on:
push:
branches: [main]
pull_request:
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: subosito/flutter-action@v2
with:
channel: stable
flutter-version: 3.24.0
cache: true
- run: flutter pub get
- name: Check formatting
run: dart format --output=none --set-exit-code .
- name: Analyze
run: flutter analyze
- name: Run tests
run: flutter test --coverage
- name: Upload coverage report
uses: actions/upload-artifact@v4
with:
name: coverage
path: coverage/lcov.infoHere is what each part does.
onruns the workflow for pushes tomainand for every pull request.flutter-versionpins the SDK. Without a pin, a new stable release can break your build with no change to your code. Update the pin on purpose, in its own commit.cache: truestores the SDK between runs, which cuts setup time.dart format --set-exit-codefails when any file is not formatted.--output=nonestops it from printing every file.flutter analyzefails on analyzer errors and, by default, on warnings and infos too. Tune this inanalysis_options.yaml, not in the workflow.
Enforcing a coverage threshold
flutter test --coverage writes coverage/lcov.info. In that file, every source file has an LF: line (lines that can run) and an LH: line (lines that did run). Adding these up gives an overall percentage. You can enforce a minimum with a short shell step:
pct=$(awk -F: '/^LF:/ {lf+=$2} /^LH:/ {lh+=$2} END {printf "%.1f", 100*lh/lf}' coverage/lcov.info)
echo "Line coverage: ${pct}%"
awk -v p="$pct" 'BEGIN { exit (p < 80) }'The last line exits with 1 when coverage is below 80, which fails the step. Add it to the workflow as another run: | step after the tests.
Be careful with what the number measures:
- Files that no test imports do not appear in
lcov.infoat all. Your coverage can look high while whole files are untested. A common workaround is atest/coverage_helper_test.dartfile that imports every file underlib/. - Generated files, such as
*.g.dart, inflate or deflate the percentage. Remove them from the report withlcov --removebefore you compute the threshold. - A threshold is a floor, not a goal. Raising it to 100 pushes people to write tests that execute code without asserting anything.
Golden tests across operating systems
Golden tests compare pixels, and text rendering differs between macOS, Linux and Windows. A golden file made on a developer's Mac often fails on a Linux CI runner by a few pixels.
You have three practical options:
| Option | How it works | Trade-off |
|---|---|---|
| Generate goldens on the CI platform | Developers update goldens through a CI job or a Linux container | Consistent, but slower local feedback |
| Tag golden tests and run them on one OS | Run them only in a single job | Simple, but golden tests are skipped locally on other systems |
| Use a tolerant comparator | Write a custom `GoldenFileComparator` that allows a small difference | Fewer false failures, but it can hide real regressions |
Tagging is the cheapest to set up. Mark the golden test file with a tag:
@Tags(['golden'])
library;
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('title matches the golden file', (tester) async {
await tester.pumpWidget(
const MaterialApp(home: Scaffold(body: Center(child: Text('Hello')))),
);
await expectLater(
find.byType(Scaffold),
matchesGoldenFile('goldens/hello.png'),
);
});
}Declare the tag in dart_test.yaml at the project root. Without this, the test runner warns about an unknown tag.
tags:
golden:Now you can split the runs:
flutter test --exclude-tags golden
flutter test --tags goldenRun the second command only on the operating system that produced the golden files. When a golden test fails, the test run writes a failures/ folder next to the golden file with the expected image, the actual image and a diff. Upload it as an artifact so reviewers can see the change without reproducing it.
Integration tests in CI
Integration tests need a running device. On Linux runners, the usual choice is an Android emulator. The community action reactivecircus/android-emulator-runner starts one and runs your command.
integration:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Enable KVM
run: |
echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules
sudo udevadm control --reload-rules
sudo udevadm trigger --name-match=kvm
- uses: actions/setup-java@v4
with:
distribution: temurin
java-version: 17
- uses: subosito/flutter-action@v2
with:
channel: stable
flutter-version: 3.24.0
cache: true
- run: flutter pub get
- uses: reactivecircus/android-emulator-runner@v2
with:
api-level: 34
arch: x86_64
script: flutter test integration_testPoints to know:
- KVM is Linux hardware acceleration. Without it the emulator is far too slow. The first step enables it on GitHub-hosted runners.
- Boot time adds minutes to every run. Put this in its own job so it does not delay the fast feedback from the
testjob. Both jobs run in parallel because neither declaresneeds. - Flakiness is the main cost of integration tests. Prefer
pumpAndSettleover fixed delays, and avoid real network calls. If your app talks to a backend, point it at a stub server or a fake. - iOS needs a macOS runner and a simulator, which costs more per minute. Many teams run iOS integration tests only on
mainor on a nightly schedule.
You can also trigger a slower job on a schedule instead of on each push:
on:
schedule:
- cron: '0 3 * * *'Common failures
- "Works on my machine." Almost always a different Flutter version. Pin it, and put the same version in your team's setup notes.
- Tests pass alone but fail together. Shared mutable state, such as a global singleton, leaks between tests. Reset it in
setUpandtearDown. Runflutter test --concurrency=1to check whether ordering or parallelism matters. - Dependency drift. Commit
pubspec.lockfor apps so CI resolves the same package versions you tested locally. Libraries usually do not commit it. - Slow pipelines. Cache the SDK and the pub cache, run the integration job in parallel, and stop in-progress runs when a new commit arrives by adding
concurrencywithcancel-in-progress: trueto the workflow. - Secret leakage. Never print API keys in test output. Use the CI provider's secret store and inject values with
--dart-define.
Finally, make the checks mandatory. In your repository settings, mark the test job as a required status check for the main branch. A CI job that people can ignore does not protect the code.
Exercise
Your golden tests pass on a teammate's Mac but fail on the Linux CI runner with tiny pixel differences. Name two safe ways to fix this, and one fix you must not use.
Show answer
Safe options: (1) tag the golden tests with @Tags(['golden']), declare the tag in dart_test.yaml, and run them only on the operating system that produced the golden files; or (2) generate and update the golden files on the CI platform (for example in a Linux container) so every comparison uses the same renderer. A tolerant custom GoldenFileComparator is also acceptable if you accept the risk of hiding small real regressions. The fix you must not use is running flutter test --update-goldens automatically in CI, because it overwrites the expected images with the current output, so every visual regression would pass.
Exercise
Why can a project report 95% line coverage in lcov.info and still have large untested areas?
Show answer
Files that no test imports are not listed in lcov.info, so they count neither as covered nor as uncovered. The percentage only reflects files that tests loaded. Adding a helper test that imports every file under lib/ makes those files appear in the report.