Sub topic 1
Where integration tests fit among unit and widget tests
Flutter's testing documentation describes three kinds of automated test: unit, widget, and integration. They differ in what they run, where they run, and what a pass tells you. This chapter explains those differences so you can decide which kind a given behavior needs. Later chapters cover setup and writing integration tests in detail.
Prerequisites
This chapter assumes you have:
- Basic Dart and Flutter app development experience.
- Familiarity with widgets, keys, and the widget tree.
- Written at least one simple widget test with
flutter_test. - Used
fluttercommands in a terminal. - A device, emulator, or simulator that Flutter can detect. You don't need one for this chapter, but you will from the next chapters on.
The three test types
Each test type answers a different question.
- A unit test asks whether one function, method, or class behaves correctly in isolation.
- A widget test asks whether one widget or small subtree builds and responds correctly to input.
- An integration test asks whether the whole app works when it runs as a user would run it.
A unit test and a widget test both run inside the Dart VM on your development machine, using the flutter_test package. An integration test builds your real app, installs it on a device, emulator, simulator, or desktop target, and drives it there. The integration_test package provides this capability. It ships with the Flutter SDK and reuses the same testWidgets, finder, and expect API you already know from widget tests.
Unit tests
A unit test calls plain Dart code and checks the result. It has no widgets, no rendering, and no device.
import 'package:flutter_test/flutter_test.dart';
int applyDiscount(int cents, int percent) => cents - (cents * percent ~/ 100);
void main() {
test('applies a 10 percent discount', () {
expect(applyDiscount(1000, 10), 900);
});
test('a 0 percent discount changes nothing', () {
expect(applyDiscount(1000, 0), 1000);
});
}Unit tests run in milliseconds. They are the right tool for pure logic: parsing, formatting, validation, state-management classes, and repository logic with mocked dependencies. They cannot tell you whether a button is wired to that logic.
Widget tests
A widget test builds a widget in a test environment and interacts with it. Here is a small counter page and a widget test for it.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
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(
body: Center(child: Text('$_count')),
floatingActionButton: FloatingActionButton(
key: const Key('increment'),
onPressed: () => setState(() => _count++),
child: const Icon(Icons.add),
),
);
}
}
void main() {
testWidgets('tapping the button increments the counter', (tester) async {
await tester.pumpWidget(const MaterialApp(home: CounterPage()));
expect(find.text('0'), findsOneWidget);
await tester.tap(find.byKey(const Key('increment')));
await tester.pump();
expect(find.text('1'), findsOneWidget);
});
}This test builds only CounterPage, wrapped in a MaterialApp that supplies the theme and navigation it needs. It runs without a device, so it is fast and works well in a tight edit-and-run loop.
Integration tests
An integration test starts the actual app by calling its real main function. The next chapters explain the setup. Here is the shape of such a test, so you can compare it with the widget test above.
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('counter works in the running app', (tester) async {
app.main();
await tester.pumpAndSettle();
await tester.tap(find.byKey(const Key('increment')));
await tester.pumpAndSettle();
expect(find.text('1'), findsOneWidget);
});
}The interactions look nearly identical to the widget test. The difference is what sits underneath: this test uses the real app entry point, real routing, real plugin implementations, and a real rendering engine on a real device. The code itself is not what makes it an integration test. The environment it runs in is.
What actually differs
The table summarizes the practical differences.
| Aspect | Unit test | Widget test | Integration test |
|---|---|---|---|
| Scope | One function or class | One widget or subtree | Whole app, multiple screens |
| Runs on | Dart VM on host | Dart VM on host | Device, emulator, simulator, or desktop |
| Rendering | None | Simulated, headless | Real engine and GPU |
| Plugins and platform channels | Not used | Not available unless mocked | Real native implementations |
| Network | Mocked | Blocked by default; mock it | Real unless you replace it |
| Typical speed | Milliseconds | Tens to hundreds of milliseconds | Seconds to minutes |
| Maintenance cost | Low | Low to medium | Higher |
| Confidence in end-to-end behavior | Low | Medium | High |
Some of these entries need explanation.
The widget-test environment is simulated
In a widget test, TestWidgetsFlutterBinding replaces parts of the framework. Time is faked, so pump(Duration) advances a clock you control. Real asynchronous work, such as timers and I/O, does not progress the way it does in a running app unless you wrap it in tester.runAsync. The binding also replaces HttpClient, so real HTTP requests fail with status 400 by default. Rendering is not done on a real GPU, so a widget test cannot reveal a shader problem or a frame drop.
Platform channels are another gap. A plugin that calls into Android or iOS code throws a MissingPluginException in a widget test unless you mock the channel. In an integration test the plugin's native code actually runs. That means camera access, secure storage, location, and permission dialogs are testable there, and nowhere else.
The integration test environment is real
The integration_test binding runs inside the app process on the target device. It uses the real engine, real scheduler, and real frames. Because the app is genuine, you can find bugs that no isolated test can:
- A plugin that is not registered on one platform.
- A missing permission entry in
AndroidManifest.xmlorInfo.plist. - A route that works in isolation but fails because an ancestor widget is missing in the real tree.
- A layout that overflows on a small physical screen.
- A startup crash caused by initialization order in
main. - Jank, measured with the profiling tools covered in a later chapter.
Cost grows with realism
Realism has a price. An integration test must build and install the app before the first assertion, which can take tens of seconds to minutes. It depends on a device being available and in a clean state. It is also more exposed to timing issues, network conditions, and operating-system dialogs. A suite made only of integration tests is slow and tends toward flakiness, meaning tests that fail on some runs for reasons unrelated to a real bug.
Choosing the right level
A useful rule is to test each behavior at the cheapest level that can actually fail for the reason you care about.
- If the bug would live in a calculation or a data transformation, write a unit test.
- If it would live in how one widget reacts to state or input, write a widget test.
- If it depends on the real platform, multiple screens, real plugins, or the app's startup, write an integration test.
Consider a login feature and the layers it could use.
| Behavior | Best level | Reason |
|---|---|---|
| Email format validation | Unit | Pure function, no UI needed |
| Error text appears under the field when email is invalid | Widget | One widget reacting to state |
| Submit button is disabled while a request is pending | Widget | Local UI state with a fake service |
| Tapping Submit with valid credentials navigates to the home screen of the real app | Integration | Spans screens, routing, and real startup |
| Token is saved to the platform's secure storage and survives an app restart | Integration | Needs the real plugin and real storage |
The testing pyramid
A common guideline is a pyramid: many unit tests at the base, fewer widget tests in the middle, and a small number of integration tests at the top. The shape reflects cost and speed. A large number of fast tests gives quick feedback, and a handful of end-to-end tests confirms the pieces fit together.
The pyramid is a heuristic, not a rule. A plugin-heavy app, such as one built around Bluetooth or the camera, may need proportionally more integration tests, because much of its risk sits where mocks can't reach. A mostly pure-Dart app may need very few.
Integration tests complement the other types
Integration tests do not make the other levels redundant. When an integration test fails, it usually tells you that something is wrong but not where. A failing unit test points at a function. A failing widget test points at one widget. A failing integration test might mean a backend change, a routing mistake, a timing issue, or a broken plugin. Keeping lower-level tests means you can diagnose problems in seconds instead of stepping through a full app run.
Equally, passing unit and widget tests do not prove the app works. Each part can be correct while the connection between them is wrong. Integration tests cover that gap.
A note on the older flutter_driver
Older Flutter projects used the flutter_driver package, which ran tests from a separate process and communicated with the app over a connection. The integration_test package replaced it as the recommended approach. Its tests run in the same process as the app and use the familiar flutter_test API, so you can reuse finders and expect calls. You may still see flutter_driver in older code, and a later chapter explains how flutter drive still has a role with integration_test for web and performance data.
Common mistakes
- Using integration tests for logic. Testing a discount calculation by tapping through five screens is slow and fragile. Move the check to a unit test.
- Mocking everything in an integration test. If every dependency is replaced, the test no longer exercises the real platform, and a widget test would have been cheaper. Replace only what is non-deterministic, such as a remote server you don't control.
- Expecting widget tests to cover plugins. A passing widget test with a mocked channel says nothing about the native side.
- Skipping lower-level tests because integration tests exist. This produces a slow suite with poor failure diagnosis.
- Treating one passing run as proof. Integration tests can be flaky. A later chapter covers stable keys, controlled test data, and explicit waits.
What comes next
The next chapter adds the integration_test package to a project, so you can write a first test that launches the real app. You will then learn how the test binding works, how to locate widgets and simulate input, and how to run everything on a physical device.
Exercise
Your app has a screen that reads the device's battery level through a plugin and shows it in a label. Which test type can verify that the label shows the real battery level, and why can't a widget test do it?
Show answer
An integration test. It runs the real app on a device, where the plugin's native code runs and returns the real value. A widget test runs on the host in a simulated environment without the native implementation, so calling the plugin throws a MissingPluginException unless you mock the channel. With a mock, the test only verifies that the label displays the mocked value, not the real battery level.
Exercise
For each behavior, name the cheapest test type that can fail for the right reason: (a) a function that converts a price in cents to a "$12.34" string, (b) a card widget that shows a "Sold out" badge when a flag is true, (c) the app starts, the user signs in, and the home screen shows their saved data read from platform storage.
Show answer
(a) Unit test, because it is pure logic. (b) Widget test, because it concerns one widget reacting to a state flag and needs no device. (c) Integration test, because it spans startup, several screens, and a real storage plugin.