Sub topic 3
The integration test binding
This chapter explains the object that makes an integration test different from a widget test: IntegrationTestWidgetsFlutterBinding. It assumes you can already write a basic testWidgets test. It also assumes integration_test is in your dev_dependencies and that Flutter can see a device or emulator.
What a binding is
A Flutter app runs on top of several singleton objects called bindings. They connect the framework to the engine and the operating system. WidgetsFlutterBinding is the one runApp uses. It schedules frames, delivers pointer events, and owns the widget tree. There is only ever one binding instance per Dart isolate. The first call to any ensureInitialized creates it, and later calls return the same object.
flutter_test uses the same mechanism. When you write testWidgets, the test framework installs a test binding in place of WidgetsFlutterBinding. Which binding it installs decides how time and rendering behave during the test.
| Binding | Installed by | Clock | Rendering | Typical use |
|---|---|---|---|---|
| `AutomatedTestWidgetsFlutterBinding` | `flutter test test/` (default) | Fake: `pump(duration)` advances time instantly | Simulated, no real frames | Widget tests |
| `LiveTestWidgetsFlutterBinding` | Explicit call, or `flutter run` style tests | Real | Real frames on a real surface | Visual debugging |
| `IntegrationTestWidgetsFlutterBinding` | `ensureInitialized()` from `integration_test` | Real | Real frames on the device | Integration tests |
IntegrationTestWidgetsFlutterBinding is a subclass of the live binding. It adds a way to send results and data from the device back to the process that launched the test.
What ensureInitialized does
You start every integration test file with one line:
IntegrationTestWidgetsFlutterBinding.ensureInitialized();That call does three jobs.
- It installs the live-style binding. Frames are real. When a test calls
await tester.pump(const Duration(seconds: 1)), one real second passes. An animation that takes 300 ms takes 300 ms on the device, because there is no fake clock to skip ahead. - It registers a result channel. Each
testWidgetsoutcome, pass or fail, is collected by the binding and sent to the host. The host isflutter testorflutter drive, running on your computer. That is how a test running on a phone produces a pass or fail exit code in your terminal. - It provides a place for extra data. The binding keeps a
reportDatamap. Performance timelines recorded withtraceActionare stored there and sent to the driver, as a later chapter shows.
The call returns the binding, so you can keep it in a variable when you need its features:
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() {
final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized();
testWidgets('the app runs on the integration binding', (tester) async {
expect(binding, isA<LiveTestWidgetsFlutterBinding>());
expect(WidgetsBinding.instance, same(binding));
app.main();
await tester.pumpAndSettle();
expect(find.byType(MaterialApp), findsOneWidget);
});
}The second expect shows the singleton rule in practice. WidgetsBinding.instance is the very object you got back. Your app's own code therefore talks to the test binding without knowing it.
How the pieces connect
The test code and the app run in the same Dart isolate on the device. That is the key difference from older driver-based testing, where the test ran on your computer and sent commands over a connection. Here the test can call find and tester.tap directly against the live widget tree.
Order matters: binding first, then the app
Call ensureInitialized() before app.main(). The reason is the singleton rule.
- If the binding is initialized first, your app's
mainmay callWidgetsFlutterBinding.ensureInitialized(). That call returns the existing integration binding, and nothing breaks. - If
app.main()ran first, a plainWidgetsFlutterBindingwould already exist. Initializing the integration binding afterward could not replace it, and you would get an error about a conflicting binding or a test that never reports results.
Put ensureInitialized() on the first line of the test file's main, before any testWidgets call. Do not place it inside a testWidgets body.
Using the binding for more than setup
Once you hold the binding, you can use its extra members. These are the ones you will meet most often.
framePolicy: controls how the live binding schedules frames while the test waits. The default policy is tuned for watching a test run. For performance work you can set it toLiveTestWidgetsFlutterBindingFramePolicy.fullyLive, so the app renders at its natural pace.traceAction: records a performance timeline while an interaction runs.reportData: a map you can fill with extra values for the driver to save.takeScreenshot: captures an image of the current screen, on platforms that support it.
Here is a test that sets the frame policy and records a timeline. It needs flutter drive to save the timeline, which a later chapter covers. Run through flutter test, it still executes, but nothing is saved.
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() {
final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized();
binding.framePolicy = LiveTestWidgetsFlutterBindingFramePolicy.fullyLive;
testWidgets('scrolling is recorded', (tester) async {
app.main();
await tester.pumpAndSettle();
final list = find.byType(Scrollable).first;
await binding.traceAction(() async {
await tester.fling(list, const Offset(0, -500), 10000);
await tester.pumpAndSettle();
}, reportKey: 'scrolling_timeline');
});
}Setting framePolicy outside testWidgets, right after ensureInitialized(), applies it to every test in the file.
Time behaves differently than in widget tests
The most common source of confusion for people moving from widget tests is the clock. A widget test uses a fake clock. A Future.delayed(Duration(seconds: 5)) in the app completes as soon as you pump past it, so the test finishes quickly. The integration binding uses real time.
Consequences:
- A 5-second delay in your app costs 5 real seconds in the test. Slow flows make slow tests.
pump(duration)waits for that duration on the real clock, then builds a frame.- Real network calls, real platform channels, and real disk access all happen. The test finishes only when they do.
- Timeouts count real time. A
testWidgetscall accepts atimeoutargument if a long flow needs more room.
testWidgets('slow startup flow', (tester) async {
app.main();
await tester.pumpAndSettle(const Duration(milliseconds: 100),
EnginePhase.sendSemanticsUpdate, const Duration(seconds: 30));
expect(find.text('Home'), findsOneWidget);
}, timeout: const Timeout(Duration(minutes: 3)));Here pumpAndSettle is given a longer ceiling of 30 seconds. Without that, it throws a timeout after its default of 10 minutes of simulated pumping, or earlier when the app never goes idle. The next chapters on pumping cover this in depth.
State that outlives a test
Every test in the file shares one process, one binding, and one isolate. That has two practical effects.
- Static fields, singletons, and service locators keep their values between tests. A user who logged in during test one is still logged in during test two, unless your code resets it.
- Calling
app.main()in each test callsrunAppagain. The new widget tree replaces the old one, but anything held outside the tree survives.
When tests depend on each other through hidden state, they pass in one order and fail in another. Reset shared state in a setUp block, or have your app expose a way to start from a clean slate. The chapter on determinism returns to this.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Test passes on the host but never runs on the device | The file was run as a plain unit test, not on a device | Pass `-d <device_id>` to `flutter test integration_test/...` |
| Error about a binding already being initialized | `app.main()` or other code initialized a different binding first | Call `ensureInitialized()` as the first line of `main` |
| Run hangs, with no result | `ensureInitialized()` is missing, so results never reach the host | Add the call at the top of the test `main` |
| Test is far slower than the same widget test | Real clock and real I/O | Reduce waits in app code for test builds, or accept the cost |
| Second test starts logged in | State kept in a singleton | Reset it in `setUp` |
Summary of the working model
- The binding is a singleton that decides how frames and time work during a test.
IntegrationTestWidgetsFlutterBinding.ensureInitialized()swaps in a live binding, enables result reporting to the host, and exposestraceActionandreportData.- Call it once per file, first, before
app.main(). - Time is real, state is shared across tests in a file, and the test code runs inside the same isolate as the app.
Exercise
A teammate's integration test file calls app.main() at the top of main() and then calls IntegrationTestWidgetsFlutterBinding.ensureInitialized() on the next line. Explain what is wrong and how to fix it.
Show answer
The binding is a singleton, and whichever initializer runs first decides which binding exists. If app.main() runs first, the app's own WidgetsFlutterBinding.ensureInitialized() creates a plain binding, so the integration binding cannot be installed afterward. Move IntegrationTestWidgetsFlutterBinding.ensureInitialized() to the first line of main(), before any call to app.main(). The app's own call then returns the existing integration binding.
Exercise
A widget test that waits for a 3-second Future.delayed in the app finishes almost instantly. The same flow as an integration test takes about 3 seconds. Why?
Show answer
Widget tests use AutomatedTestWidgetsFlutterBinding, which has a fake clock, so pumping past the delay completes it at once. The integration binding is a live binding that uses the real clock and real frames, so the 3-second delay takes 3 real seconds.
Exercise
Write the first lines of an integration test file's main that initialize the binding, keep a reference to it, and set the frame policy to fully live.
Show answer
void main() { final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized(); binding.framePolicy = LiveTestWidgetsFlutterBindingFramePolicy.fullyLive; // testWidgets calls follow }