Sub topic 8
Organizing test files, groups and setup
This chapter assumes you can write a single integration test with IntegrationTestWidgetsFlutterBinding, find widgets by key, and run a file on a device with flutter test. It also assumes you know group, setUp and tearDown from flutter_test. One test file works fine for a first run. A suite with login, checkout and settings flows needs a layout, shared helpers and a plan for resetting app state between tests.
A directory layout that scales
The flutter test integration_test command looks for files ending in _test.dart under the integration_test directory, including subdirectories. Files that do not end in _test.dart are ignored, so you can keep helpers next to the tests without them being run as tests.
integration_test/
app_test.dart # optional aggregator, see below
flows/
login_test.dart
checkout_test.dart
settings_test.dart
support/
app_launcher.dart # launch and reset helpers
robots/
login_robot.dart # page-style helpers
lib/
test_keys.dart # keys shared by app code and testsThree rules keep this layout manageable:
- Name a test file after the user flow it covers, not after a class or screen.
checkout_test.dartages better thancart_page_test.dart. - Keep anything that is not a test out of
*_test.dartfiles. Helpers go insupport/. - Put widget keys in one shared file so the app and the tests cannot drift apart.
// lib/test_keys.dart
import 'package:flutter/widgets.dart';
abstract final class AppKeys {
static const emailField = Key('email_field');
static const submitButton = Key('submit_button');
static const incrementButton = Key('increment');
}In the app, use key: AppKeys.emailField on the widget. In the tests, call find.byKey(AppKeys.emailField). Renaming a key is then a compile-time change in both places. With string literals it silently breaks a test.
What each test file costs
Each file in integration_test/ is a separate test entry point. When you run flutter test integration_test, Flutter builds and installs the app once per file on a real device. This has two consequences:
- Files are isolated from each other. Every file starts with a fresh process, so state cannot leak between files.
- Many small files make the run slow. The build and install step often takes longer than the test itself.
Inside one file, the opposite holds. All tests share one process and one binding, so anything global, such as singletons, in-memory caches, or a logged-in session, survives from one test to the next. Keep both facts in mind when you decide where to split.
| Approach | Isolation | Speed | Good for |
|---|---|---|---|
| One file per flow | Strong, fresh process per file | Slower, one build per file | Flows with heavy global state, small suites |
| One aggregator file importing all flows | Weak, one process for all tests | Faster, one build | Larger suites, `flutter drive`, device farms billed per run |
Groups for structure
group works as it does in any Dart test. It adds a name prefix to the report and scopes setUp and tearDown callbacks. In integration tests, grouping by feature or screen makes failure output on a device much easier to read. A failed test is reported as login shows an error for an empty email, which tells you where to look.
Keep groups shallow. Two levels, feature then scenario, is usually enough. Deeper nesting spreads setup across several scopes, and you then have to read all of them to know what state a test starts in.
Setup and teardown order
The callbacks run in this order for a group containing two tests:
setUpAllruns once before the first test in its group. Use it for expensive, read-only preparation such as seeding a test account on a backend.setUpruns before every test in its group. Outer groups run before inner groups.tearDownruns after every test. Inner groups run before outer groups.tearDownAllruns once after the last test.
There is one limit that surprises people. setUp and setUpAll do not receive a WidgetTester. You cannot call tester.pumpAndSettle() or launch the app with app.main() and wait for it inside a setUp. Anything that needs the tester has to run inside the test body, or inside a helper that the test body calls.
A launcher helper instead of repeated setup
Every test in a flow starts the same way: reset persistent state, launch the app, wait for the first frame. A small wrapper around testWidgets removes that repetition and guarantees no test forgets the reset.
This example clears shared_preferences. If your app stores data elsewhere, such as a database file, a secure storage entry or a backend session, clear those instead. The example needs shared_preferences in dependencies.
// integration_test/support/app_launcher.dart
import 'package:flutter_test/flutter_test.dart';
import 'package:my_app/main.dart' as app;
import 'package:shared_preferences/shared_preferences.dart';
/// Clears persisted state so each test starts like a first launch.
Future<void> resetAppState() async {
final prefs = await SharedPreferences.getInstance();
await prefs.clear();
}
/// Like testWidgets, but resets state and launches the real app first.
void testApp(
String description,
Future<void> Function(WidgetTester tester) body,
) {
testWidgets(description, (tester) async {
await resetAppState();
app.main();
await tester.pumpAndSettle();
await body(tester);
});
}Now a flow file reads like a list of scenarios:
// integration_test/flows/login_test.dart
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:my_app/test_keys.dart';
import '../support/app_launcher.dart';
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
group('login', () {
testApp('shows a welcome message after a valid login', (tester) async {
await tester.enterText(
find.byKey(AppKeys.emailField),
'[email protected]',
);
await tester.tap(find.byKey(AppKeys.submitButton));
await tester.pumpAndSettle();
expect(find.text('Welcome'), findsOneWidget);
});
testApp('shows an error when the email is empty', (tester) async {
await tester.tap(find.byKey(AppKeys.submitButton));
await tester.pumpAndSettle();
expect(find.text('Email is required'), findsOneWidget);
expect(find.text('Welcome'), findsNothing);
});
});
}The texts Welcome and Email is required come from the example app. Replace them with the strings your app shows.
The reset happens before the launch, so the app reads clean storage at startup. Resetting after the launch would be too late for anything the app loads in main.
Repeated launches in one process
Calling app.main() in every test works for most apps, because runApp replaces the previous widget tree. It does not reset Dart-level globals. A static field, a service locator registration or a cached repository keeps its value from the previous test. If your app has any of these, do one of the following:
- Expose a reset function from the app and call it inside
resetAppState. - Change
mainto build its dependencies in a function you can call again, and have the launcher call that function. - Put the affected flows in separate files, so each gets a fresh process.
Option 3 needs no app changes, but it pays the build cost described earlier.
Page-style helpers
When several tests perform the same sequence of steps, move the steps into a helper class, often called a robot. It holds a WidgetTester and exposes methods named after user actions.
// integration_test/support/robots/login_robot.dart
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:my_app/test_keys.dart';
class LoginRobot {
LoginRobot(this.tester);
final WidgetTester tester;
Future<void> signIn(String email) async {
await tester.enterText(find.byKey(AppKeys.emailField), email);
await tester.tap(find.byKey(AppKeys.submitButton));
await tester.pumpAndSettle();
}
void expectWelcome() {
expect(find.text('Welcome'), findsOneWidget);
}
}A test then becomes two lines: final login = LoginRobot(tester); await login.signIn('[email protected]');. Put the pumpAndSettle calls inside the helper, so tests cannot forget to wait after an action. Do not hide assertions in helpers that do something else. A method named signIn that also asserts is hard to reuse in a test where sign-in is expected to fail.
Combining files with an aggregator
To build and install once for the whole suite, create an aggregator file that imports each flow and registers its main as a group:
// integration_test/app_test.dart
import 'package:integration_test/integration_test.dart';
import 'flows/checkout_test.dart' as checkout;
import 'flows/login_test.dart' as login;
import 'flows/settings_test.dart' as settings;
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
group('login', login.main);
group('checkout', checkout.main);
group('settings', settings.main);
}This needs import 'package:flutter_test/flutter_test.dart'; as well, because group comes from there. Add that line to the top of the file.
Calling ensureInitialized in both the aggregator and each flow is safe. The call returns the existing binding when one already exists. Each flow file also still works on its own, so you can run just integration_test/flows/login_test.dart while developing.
The aggregator is also the natural target for flutter drive, which runs one --target file per invocation. Later chapters cover that command.
If you run flutter test integration_test with the aggregator present, the flow files are also run on their own, because they end in _test.dart. That runs every flow twice. To avoid this, pass the aggregator path explicitly (flutter test integration_test/app_test.dart -d <device_id>), or name the flow files without the _test suffix, for example login_flow.dart. The aggregator then stays the only test entry point.
Choosing a structure
Use these criteria as a starting point:
- Start with one file per flow and a shared
support/directory. This is the simplest layout and gives the strongest isolation. - Move to an aggregator when the per-file build time dominates your run, or when your CI or device farm bills or limits by run.
- Move a flow back into its own file if it needs a fresh process, for example because it tests first-launch behavior or leaves global state behind.
- Keep every test independent. If you cannot run a test alone and get the same result, fix the test before restructuring files.
Exercise
Your suite has ten flow files. Every flutter test integration_test run takes much longer than the tests themselves, and the time grows with each new file. Why, and what two changes would you consider?
Show answer
Each file in integration_test/ is its own entry point, so Flutter builds and installs the app once per file. The build time repeats ten times. You can create an aggregator file that imports each flow and registers its main with group, and run only that file, so the app builds once. Alternatively, merge small flows into fewer files. The cost of both is weaker isolation, because all tests then share one process and any global state must be reset explicitly.
Exercise
A teammate puts app.main(); await tester.pumpAndSettle(); inside a setUp callback. What happens, and where should the code go instead?
Show answer
It does not compile in a useful form, because setUp does not receive a WidgetTester, so there is no tester to call pumpAndSettle on. Launching and settling must happen inside the test body. Put them in a helper such as testApp, which wraps testWidgets, resets persisted state, calls app.main(), settles the first frame, and then runs the test's own body.