Sub topic 2
Setting up and running tests
This chapter covers the project pieces a Flutter test suite needs: dependencies, file layout, and the commands that run the tests. It assumes you can write basic Dart with async and await, have built small Flutter apps, use the flutter command line tool, and can edit pubspec.yaml. Later chapters cover writing the tests themselves. Here the goal is a suite that runs and fails for reasons you understand.
What `flutter test` does
flutter test compiles your test files and runs them on your development machine, not on a phone or emulator. It uses a headless test environment, which means there is no real screen. Widgets are built and laid out, but nothing is drawn to a display.
This is why unit and widget tests run in seconds. It also means these tests cannot call real platform features such as the camera or a plugin that talks to Android or iOS code. Integration tests, covered in a later chapter, are the layer that runs on a real device or emulator.
Declaring test dependencies
Test packages belong in dev_dependencies, so they are not shipped in your app. A project created with flutter create already contains the first entry below.
dev_dependencies:
flutter_test:
sdk: flutter
integration_test:
sdk: flutter
mocktail: ^1.0.4
flutter_lints: ^5.0.0Each entry has a different job:
| Package | Purpose |
|---|---|
| `flutter_test` | Provides `test`, `group`, `expect`, `testWidgets`, `WidgetTester` and the finders. It ships with the Flutter SDK. |
| `integration_test` | Runs tests inside the real app on a device or emulator. Also ships with the SDK. |
| `mocktail` | Creates mock objects without code generation. Used in the test doubles chapter. |
| `flutter_lints` | Not a test package. It is a lint rule set that the default template includes. |
You can add a package from the command line instead of editing the file:
flutter pub add --dev mocktailAfter editing pubspec.yaml by hand, run flutter pub get. flutter test also runs it for you unless you pass --no-pub.
`flutter_test` versus `test`
flutter_test re-exports the core of Dart's test package, so test, group, setUp and expect come from one import:
import 'package:flutter_test/flutter_test.dart';Do not add the test package alongside flutter_test in a Flutter project. Flutter pins a specific version of test internally, and a separate constraint often causes version-solving errors on flutter pub get.
Where test files go
Flutter follows a convention, and the test runner enforces part of it:
- Test files live in the
test/directory at the project root. - Every test file name must end in
_test.dart. A file namedcounter.dartintest/is not run. - Mirroring the
lib/structure undertest/is common, solib/src/counter.dartis tested bytest/src/counter_test.dart. - Integration tests live in
integration_test/, also with the_test.dartsuffix.
A typical layout looks like this:
my_app/
lib/
main.dart
src/
calculator.dart
test/
src/
calculator_test.dart
widgets/
home_page_test.dart
integration_test/
app_test.dart
pubspec.yamlEach file under test/ has its own main() function and runs as a separate unit. Global variables in one test file are not visible in another.
A first runnable test
To confirm the setup works, create a small function and a test for it. Save this as lib/src/calculator.dart:
int add(int a, int b) => a + b;Then save this as test/src/calculator_test.dart. Replace my_app with the name: value from your pubspec.yaml.
import 'package:flutter_test/flutter_test.dart';
import 'package:my_app/src/calculator.dart';
void main() {
test('add returns the sum of two numbers', () {
expect(add(2, 3), 5);
});
}Run it from the project root:
flutter testYou should see a line such as All tests passed! and a count of tests run. If you change 5 to 6 and run again, the output shows the test name, the expected value, the actual value, and the line of the failed expect.
Running tests: the commands you will use
The commands below cover almost all daily work. They are the same ones listed in this tutorial's command reference.
flutter test
flutter test test/counter_test.dart
flutter test --coverage
flutter test --update-goldens
flutter test integration_testEverything, one file, or one directory
flutter test with no arguments runs every _test.dart file under test/. Pass a file path to run one file, or a directory path such as flutter test test/widgets to run everything below it. You can pass several paths in one command.
Note that integration_test/ is not part of the default run. Plain flutter test only looks in test/.
Selecting tests by name
Two flags filter by test name, and they differ in how they match:
flutter test --plain-name "starts at zero"
flutter test --name "Counter.*increment"--plain-namematches a substring of the full test name.--nametreats its value as a regular expression.
The full name of a test includes the names of the groups around it, joined by spaces. A test called increment adds one inside group('Counter', ...) has the full name Counter increment adds one. This is a common reason a --plain-name filter matches nothing: the learner types only the inner test name with the wrong spacing or forgets that the group name is part of the string.
Tags
You can label tests and select them by label. Declare tags in a dart_test.yaml file at the project root:
tags:
slow:Apply a tag in the test and filter on it:
import 'package:flutter_test/flutter_test.dart';
void main() {
test('parses a large file', () {
expect(1 + 1, 2);
}, tags: 'slow');
}flutter test --tags slow
flutter test --exclude-tags slowIf you use a tag that is not declared in dart_test.yaml, the runner prints a warning. Declaring tags keeps the list of labels in one place.
Output and speed
--reporter expandedprints one line per test as it finishes.--reporter compactis the default in a terminal.--reporter githubformats output for GitHub Actions annotations.--concurrency=Nsets how many test files run at the same time. The default is based on your processor count. Lowering it to1helps when you suspect tests interfere with each other through shared files or ports.--no-pubskips the automaticpub get, which saves a moment in repeated runs.
Coverage and golden files
flutter test --coverage writes coverage data to coverage/lcov.info. Only files that the tests import are listed, so a source file no test touches does not appear as 0% covered. It is simply absent. The coverage chapter returns to this.
flutter test --update-goldens rewrites the stored reference images used by golden tests. Run it deliberately and review the changed images before committing them, because it accepts whatever the widget currently looks like.
Integration tests
flutter test integration_testThis command needs a target device. With one device connected or one emulator running, Flutter picks it automatically. If several are available, choose one with -d:
flutter devices
flutter test integration_test -d emulator-5554The device ID comes from the flutter devices output. The id emulator-5554 is only an example.
Common setup errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `No tests were found` or `Test directory "test" not found` | No `test/` folder, or file names do not end in `_test.dart` | Create the folder and rename the file |
| `Target of URI doesn't exist: 'package:flutter_test/flutter_test.dart'` | `flutter_test` missing from `dev_dependencies` | Add it with `sdk: flutter`, then run `flutter pub get` |
| `Target of URI doesn't exist: 'package:mocktail/mocktail.dart'` | Package not added | Run `flutter pub add --dev mocktail` |
| `Could not find package ... sdk: flutter` style errors in `dart test` | Using `dart test` on a Flutter project | Use `flutter test` |
| Version solving failed after adding `test` | Extra `test` dependency conflicts with Flutter's pinned version | Remove it and import `flutter_test` |
| Integration test: `No devices found` | No emulator or device running | Start one, then check `flutter devices` |
Reading a failure
A failed expect prints three things that you should read in order: the test's full name, the Expected: and Actual: lines, and a stack trace whose first line inside test/ points to the failing assertion. Start with the expected and actual values. Most setup-stage failures are one of two kinds: the code under test returned something different, or the test never ran the code you meant it to run.
Also check the exit code. A passing run exits with 0 and a failing run exits with a non-zero value. Scripts and continuous integration systems use that code to decide whether a build passed, so you rarely need to parse the text output.
Exercise
You have a file test/utils/format.dart containing a correct test, and flutter test reports that no tests were found. Name the problem and the fix. Then give the command that runs only the tests whose full name contains parses dates.
Show answer
The file name does not end in _test.dart, so the runner ignores it. Rename it to test/utils/format_test.dart. To run only the matching tests, use flutter test --plain-name "parses dates". Use --name instead if you want a regular expression.
Exercise
Why does plain flutter test not run the files in integration_test/, and what command runs them?
Show answer
Plain flutter test only searches the test/ directory, and it runs tests in a headless environment on your machine. Integration tests need a real device or emulator, so you run them explicitly with flutter test integration_test, adding -d <device id> if more than one device is available.