Sub topic 4
Writing your first integration test
This chapter walks through writing a first integration test, running it, and reading the result. It assumes you can write a basic widget test with flutter_test, understand keys and the widget tree, and run flutter commands in a terminal. It also assumes Flutter can detect at least one device, emulator, simulator or desktop target. Earlier chapters covered the dependency setup and the binding. Here they come together in one working test.
What the test will do
An integration test launches your real app on a device and drives it the way a user would. Your first test will do four things:
- Start the app by calling its
mainfunction. - Wait for the first screen to appear.
- Tap a button.
- Check that the screen changed.
The pattern is the same for every integration test you write later: start the app, wait, act, wait, assert.
The app under test
The test needs an app to drive. Use this small counter app in lib/main.dart. It matches the project name my_app that the test imports. The only change from the Flutter starter app is a Key on the button.
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(home: CounterPage());
}
}
class CounterPage extends StatefulWidget {
const CounterPage({super.key});
@override
State<CounterPage> createState() => _CounterPageState();
}
class _CounterPageState extends State<CounterPage> {
int _count = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Counter')),
body: Center(
child: Text(
'$_count',
style: Theme.of(context).textTheme.headlineMedium,
),
),
floatingActionButton: FloatingActionButton(
key: const Key('increment'),
onPressed: () => setState(() => _count++),
child: const Icon(Icons.add),
),
);
}
}The Key('increment') matters. An icon has no text, so a key is the most reliable way to find the button. Keys also keep working if you later change the icon or add a tooltip.
Project setup
Integration tests need two packages in pubspec.yaml. Both ship with the Flutter SDK, so you declare them with sdk: flutter.
dev_dependencies:
flutter_test:
sdk: flutter
integration_test:
sdk: flutterPut your test files in a top-level integration_test/ directory, next to lib/ and test/. Name each file with a _test.dart suffix. Create integration_test/app_test.dart for this chapter.
The first test
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('tapping the button increments the counter', (tester) async {
app.main();
await tester.pumpAndSettle();
expect(find.text('0'), findsOneWidget);
await tester.tap(find.byKey(const Key('increment')));
await tester.pumpAndSettle();
expect(find.text('1'), findsOneWidget);
});
}Reading it line by line
The imports. flutter_test provides testWidgets, find, expect and the WidgetTester. integration_test provides the binding. The import package:my_app/main.dart as app gives you the app's real main function. The my_app part must match the name: field in your pubspec.yaml. If you named the project something else, change it here.
ensureInitialized(). This call installs the integration test binding as the global test binding. It must run before any testWidgets call, so it goes at the top of main. The binding is what lets the test run inside the real app process on the device and report results back to the flutter tool. If you forget it, the test either fails to connect to the tool or runs under the plain widget-test binding. The plain binding fakes the clock and the rendering, so you would not be testing on the real device.
testWidgets. This is the same function you use in widget tests. It gives you a WidgetTester, which is your handle for finding widgets, interacting with them and advancing frames.
app.main(). This starts the app exactly as it would start in production, by calling runApp. You do not call tester.pumpWidget with a widget you built yourself. That is the main difference from a widget test. In a widget test you build a small piece of the tree. Here the whole app starts, including any setup code in your main.
pumpAndSettle(). Starting the app schedules work, but nothing is on screen until frames run. pumpAndSettle keeps pumping frames until no more are scheduled, so the first screen is fully built when it returns. The next chapter covers pumping in detail. For now, treat it as "wait until the UI stops changing."
expect(find.text('0'), findsOneWidget). This checks the starting state. Asserting the starting state first is worth the extra line. If the later assertion fails, you know whether the app started wrong or the tap did nothing.
tester.tap(...). This sends a pointer down and up event at the center of the widget that the finder located. The tap goes through Flutter's normal hit testing, so a widget covered by another widget will not receive it.
The final pumpAndSettle() and expect. The tap calls setState, which schedules a frame. Pumping lets that frame run before you look at the tree.
Running the test
First list the devices Flutter can see.
flutter devicesThe output shows a name, an id and a platform for each target. Copy the id of the one you want, then run the test.
flutter test integration_test/app_test.dart -d <device_id>Replace <device_id> with the id from the first command. The first run builds the app, installs it on the device and starts it, which can take a few minutes. Later runs are faster. When the test passes, the tool prints All tests passed!. On a real phone you will also see the app open and the counter change.
You can pass a directory instead of a file, for example flutter test integration_test -d <device_id>. That runs every test file in the directory, one after another.
What happens when the test runs
The test does not run on your computer. The flutter tool builds a special version of the app that contains your test code. It installs that build on the device and starts it. The test then runs inside the app's own process, and the binding sends results back to your terminal. This is why the test sees real rendering, real plugins and real platform behavior. It is also why the first run is slow.
Common errors and how to read them
The first failures are usually setup problems, not logic problems. This table lists the ones you are most likely to see.
| Symptom | Likely cause | Fix |
|---|---|---|
| `Target of URI doesn't exist: 'package:integration_test/integration_test.dart'` | The dependency is missing | Add `integration_test` under `dev_dependencies`, then run `flutter pub get` |
| `Target of URI doesn't exist: 'package:my_app/main.dart'` | The import uses the wrong package name | Use the `name:` value from `pubspec.yaml` |
| Test hangs and then reports a timeout | No device is connected, or the app crashed during startup | Run `flutter devices` and check the device log |
| `Expected: exactly one matching candidate`, `Actual: _TextFinder:<zero widgets with text "1">` | The tap missed, or no frame ran after it | Check the key, and check that `pumpAndSettle` follows the tap |
| `Expected: exactly one matching candidate`, `Actual: found 2 widgets` | The finder is too broad | Find by key, or find within a specific ancestor |
| `pumpAndSettle timed out` | Something animates forever, such as a spinner | Pump a fixed duration with `pump(Duration(...))` instead |
Read a failed expect carefully. The message includes the finder and the number of widgets it matched. That number tells you whether the widget is missing or ambiguous.
Edge cases to know about now
App state can leak between tests. Calling app.main() inside every testWidgets is fine for a single test. With several tests in one file, they share one app process. Singletons, static fields and data saved with plugins such as shared_preferences survive from one test to the next. Reset them at the start of each test, or you will get failures that depend on test order. Later chapters cover structure and setup.
Your main may do work before runApp. If your real main initializes Firebase, reads a config file or signs a user in, app.main() does all of that too. On a real device this may need network access or credentials. Many teams split main into a thin entry point and a function such as runMyApp(config). The test then calls the second function with test settings.
Do not wrap app.main() in await. In the starter app main returns void, so there is nothing to wait for. If your main is async and returns a Future, awaiting it is fine, but you still need pumpAndSettle afterward to let the first frame appear.
Real devices are slower than the widget-test clock. In a widget test, time is simulated. On a device, frames take real time. An assertion that passes on a fast desktop target may fail on an old phone if you did not wait for the UI to settle. This is the main reason to pump after every interaction.
Checklist for a new integration test
- The file is in
integration_test/and ends in_test.dart. IntegrationTestWidgetsFlutterBinding.ensureInitialized()runs first inmain.- The test starts the real app through its entry point, then pumps.
- Every interaction is followed by a pump before the next assertion.
- Widgets you interact with have stable keys.
- You assert the starting state before you act.
Exercise
Your test file has this body: app.main(); await tester.tap(find.byKey(const Key('increment'))); expect(find.text('1'), findsOneWidget);. It fails with "zero widgets with key increment". The key does exist in the app. What is wrong, and how do you fix it?
Show answer
The test taps before the first frame has been built, so the button is not in the widget tree yet. Add await tester.pumpAndSettle(); right after app.main();. Also add one after the tap so the setState result is drawn before the expect.
Exercise
You run flutter test integration_test/app_test.dart with an Android phone and an iOS simulator both connected. What happens, and what should you do in a CI script?
Show answer
The tool asks you to choose a device, which blocks a script that has nobody to answer. Pass -d <device_id>, with the id taken from flutter devices, so the target is explicit.
Exercise
Why does an integration test call app.main() instead of tester.pumpWidget(const MyApp())?
Show answer
app.main() runs the app's real entry point, including any startup code before runApp, so the test covers the app as users launch it. pumpWidget builds only the widget you pass and skips that startup code.