Sub topic 1
Where integration tests fit among unit and widget tests
Prerequisites
This chapter assumes you know basic Dart and Flutter app development, can write a widget test with flutter_test, understand widgets and keys, and can run flutter commands in a terminal. You also need a device, emulator, or simulator that Flutter detects.
Where integration tests fit
Flutter projects usually use three kinds of tests. Unit tests check a single function or class without any UI. Widget tests build one widget or a small tree in a fast test environment. Integration tests run the full app on a real device or emulator and check a complete user flow, such as logging in and reaching a home screen.
Each layer costs more to run than the one below it, so keep most checks at the unit and widget level and use integration tests for a few critical journeys.
Adding integration_test to your project
The integration_test package ships with the Flutter SDK. Add it to dev_dependencies in pubspec.yaml, then create an integration_test directory at the project root.
dev_dependencies:
flutter_test:
sdk: flutter
integration_test:
sdk: flutterRun flutter pub get after saving the file.
The integration test binding
A binding is the object that connects the test framework to the Flutter engine. IntegrationTestWidgetsFlutterBinding is the binding for integration tests. You call ensureInitialized() once at the start of main() so the tests run against the real engine and device instead of a simulated one.
Writing your first integration test
Create integration_test/app_test.dart. The test starts your real app through its main function and checks the first screen.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:my_app/main.dart' as app;
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
testWidgets('app shows the counter at zero', (tester) async {
app.main();
await tester.pumpAndSettle();
expect(find.text('0'), findsOneWidget);
});
}Replace my_app with the name in your pubspec.yaml. The pumpAndSettle call waits until animations finish before the assertion runs.
Exercise
Exercise
Why does the test call IntegrationTestWidgetsFlutterBinding.ensureInitialized() before any test runs?
Show answer
It connects the test framework to the Flutter engine so the test runs the real app on a device. Without it, the binding is not set up and the test cannot run.