Testing
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
Flutter ships its test tooling in the SDK: package:test for plain Dart, flutter_test for widgets, and
integration_test for whole-app runs on a device. Trailhead uses all three, plus mocktail 1.0.5 for fakes. This
page builds on the layers from Data, Storage and Networking and
State Management, and its output feeds the pipeline in
Building and Releasing. Compare with the approach in
React Native and the shared-logic tests of
Kotlin Multiplatform; the overview is in
Hybrid Apps.
The Test Pyramid
| Level | Runs with | Typical Trailhead target |
|---|---|---|
Unit |
|
|
Widget |
|
|
Golden |
|
Visual regression of a trail card. |
Integration |
|
Sign in, search, open a trail, log a hike. |
Files live under test/ and end in _test.dart; integration tests live under integration_test/.
Unit Tests
import 'package:flutter_test/flutter_test.dart';
import 'package:trailhead/models/trail.dart';
void main() {
group('Trail.fromJson', () {
test('parses an integer length as a double', () {
final trail = Trail.fromJson({
'id': 't1',
'name': 'Ridge Walk',
'lengthKm': 3,
'difficulty': 'easy',
});
expect(trail.lengthKm, 3.0);
expect(trail.difficulty, 'easy');
});
test('throws when a required field is missing', () {
expect(() => Trail.fromJson({'id': 't1'}), throwsA(isA<TypeError>()));
});
});
}
Run everything with flutter test, one file with flutter test test/models/trail_test.dart, or filter by name with
flutter test --name "parses an integer".
Mocking with mocktail
mocktail needs no code generation. Create a class that extends Mock and implements the interface:
import 'package:mocktail/mocktail.dart';
class MockTrailRepository extends Mock implements TrailRepository {}
void main() {
late MockTrailRepository repo;
setUp(() {
repo = MockTrailRepository();
});
test('getTrail returns a failure when offline', () async {
when(() => repo.getTrail('t1'))
.thenAnswer((_) async => const Failure(OfflineError()));
final result = await repo.getTrail('t1');
expect(result, isA<Failure<Trail>>());
verify(() => repo.getTrail('t1')).called(1);
});
}
Use registerFallbackValue for custom argument types passed to any(). A hand-written fake class is often
simpler than a mock when the behaviour is stateful, for example an in-memory repository.
Widget Tests
testWidgets builds a widget tree in a test environment and gives you a WidgetTester to interact with it:
testWidgets('search filters the trail list', (tester) async {
await tester.pumpWidget(
MaterialApp(
home: TrailListView(
trails: const [
Trail(id: '1', name: 'Ridge Walk', lengthKm: 3, difficulty: 'easy'),
Trail(id: '2', name: 'Summit Loop', lengthKm: 12, difficulty: 'hard'),
],
),
),
);
expect(find.text('Ridge Walk'), findsOneWidget);
expect(find.text('Summit Loop'), findsOneWidget);
await tester.enterText(find.byType(TextField), 'summit');
await tester.pump(); // rebuild after the state change
expect(find.text('Ridge Walk'), findsNothing);
expect(find.text('Summit Loop'), findsOneWidget);
});
Finders and interactions
| API | Purpose |
|---|---|
find.text('x'), |
Locate widgets by text, class or key. Keys are the most stable choice. |
|
Locate by icon or tooltip. |
|
Simulate user input. |
|
Matchers for |
pump versus pumpAndSettle
pump() renders exactly one frame; pump(Duration) advances the fake clock. pumpAndSettle() keeps pumping until no
frames are scheduled, which is convenient for animations and route transitions but never returns if something
animates forever (a spinner, a repeating animation), so prefer pump() with an explicit duration there.
Riverpod in Tests
Wrap the widget in a ProviderScope with overrides to inject fakes; no global state leaks between tests:
testWidgets('shows cached trails when offline', (tester) async {
final repo = MockTrailRepository();
when(() => repo.watchTrails()).thenAnswer(
(_) => Stream.value(const Success([
Trail(id: '1', name: 'Ridge Walk', lengthKm: 3, difficulty: 'easy'),
])),
);
await tester.pumpWidget(
ProviderScope(
overrides: [trailRepositoryProvider.overrideWithValue(repo)],
child: const MaterialApp(home: TrailListScreen()),
),
);
await tester.pump();
expect(find.text('Ridge Walk'), findsOneWidget);
});
For logic without widgets, create a ProviderContainer directly and dispose it after the test:
test('favourites toggles', () {
final container = ProviderContainer(
overrides: [trailRepositoryProvider.overrideWithValue(FakeTrailRepository())],
);
addTearDown(container.dispose);
container.read(favouritesProvider.notifier).toggle('t1');
expect(container.read(favouritesProvider), contains('t1'));
});
Golden Tests
A golden test renders a widget and compares it pixel by pixel with a stored image:
testWidgets('TrailCard matches golden', (tester) async {
await tester.pumpWidget(
const MaterialApp(
home: Scaffold(
body: TrailCard(
trail: Trail(id: '1', name: 'Ridge Walk', lengthKm: 3, difficulty: 'easy'),
),
),
),
);
await expectLater(find.byType(TrailCard), matchesGoldenFile('goldens/trail_card.png'));
});
flutter test --update-goldens # create or refresh the reference images
Rendering differs slightly between operating systems, so generate and verify goldens on the same platform (usually the CI runner) or use a golden-comparison package that tolerates small differences.
Platform Channels in Tests
Plugins that talk to native code do not work in a plain flutter test. Either hide them behind your own interface
and fake it (preferred), or register a mock handler for the channel through the test binding’s messenger. See
Platform Integration.
Integration Tests
integration_test is an SDK package that runs the real app on a device, an emulator, or a simulator:
dev_dependencies:
flutter_test:
sdk: flutter
integration_test:
sdk: flutter
mocktail: ^1.0.5
import 'package:integration_test/integration_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:trailhead/main.dart' as app;
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
testWidgets('search and open a trail', (tester) async {
app.main();
await tester.pumpAndSettle();
await tester.enterText(find.byType(TextField), 'ridge');
await tester.pumpAndSettle();
await tester.tap(find.text('Ridge Walk'));
await tester.pumpAndSettle();
expect(find.text('Ridge Walk'), findsWidgets);
});
}
flutter test integration_test # on the connected device
flutter test integration_test -d <device-id> # a specific device
The flutter drive command with a driver script is the older way to run these and is still used for web, and for
reports sent to device farms such as Firebase Test Lab. On a farm you upload the built app and test bundle, and the
service runs them across many real devices.
Coverage
flutter test --coverage
# writes coverage/lcov.info
genhtml coverage/lcov.info -o coverage/html # needs lcov installed
lcov.info can be uploaded to Codecov or SonarQube. Coverage counts only files loaded by tests, so include a test
that imports the library, or accept that untested files are absent from the report.
Practical Guidance
-
Put logic in plain Dart classes: unit tests are faster than widget tests, and widget tests are faster than integration tests.
-
Give interactive widgets a
Keyso finders survive text changes and localisation. -
Avoid real time and network in tests; inject a clock or a fake repository.
-
Run
flutter analyzeanddart format --set-exit-if-changed .next to the tests in CI.
The commands in this page are summarised in the Flutter Cheat Sheet.