Sub topic 9
Making Tests Deterministic and Avoiding Flakiness
This chapter assumes you can write a basic Flutter widget test, use keys, and run flutter test on an emulator or physical device. The examples use integration_test and a real app.
A deterministic test produces the same result every time when the app and test inputs are unchanged. A flaky test sometimes passes and sometimes fails without a relevant code change. Flaky tests often come from timing, network data, animations, shared state, or selectors that change when the UI changes.
Use stable selectors
A finder should identify the intended widget without depending on layout details or translated text. A Key is a stable identifier attached to a widget for this purpose.
ElevatedButton(
key: const Key('increment'),
onPressed: _increment,
child: const Text('Add'),
)The integration test can now find the button even if its label or position changes:
await tester.tap(find.byKey(const Key('increment')));
await tester.pumpAndSettle();
expect(find.text('1'), findsOneWidget);Prefer keys that describe the widget's role, such as email_field or submit_button. Avoid generated values, list indexes, and deeply nested finders such as “the third button inside the first column.” These selectors break when the design changes.
Control test data
A test that depends on a live server can fail because of a timeout, changed data, or an unavailable service. Give the app a test configuration that uses predictable data.
Common approaches include:
- Pointing the app at a local test server.
- Loading a fixed fixture, which is a saved sample response.
- Using a test account with known permissions and data.
- Clearing or recreating the account before each test.
- Disabling random recommendations, rotating banners, and time-sensitive content.
The test should own the state it needs. Do not assume that a previous test left the application on a particular screen or that a database still contains a particular record.
Wait for state, not arbitrary time
A fixed delay such as Future.delayed(const Duration(seconds: 2)) guesses how long an operation will take. It makes fast runs slower and slow runs unreliable.
Use frame pumping after an interaction:
await tester.tap(find.byKey(const Key('submit_button')));
await tester.pumpAndSettle();
expect(find.byKey(const Key('welcome_message')), findsOneWidget);pump advances the Flutter test clock by one frame or by a specified duration. pumpAndSettle repeatedly pumps frames until there are no scheduled frames. It is useful after navigation, button taps, and finite animations.
pumpAndSettle can hang when the app has a repeating animation, an indeterminate progress indicator, or a continuously running timer. In those cases, pump a known duration and assert an intermediate state:
await tester.tap(find.byKey(const Key('refresh_button')));
await tester.pump(const Duration(milliseconds: 300));
expect(find.byType(CircularProgressIndicator), findsOneWidget);
await tester.pump(const Duration(seconds: 1));
expect(find.byKey(const Key('results')), findsOneWidget);For network-backed flows, wait for a visible state transition rather than sleeping. If the application exposes a test-only synchronization hook, use it to wait until the request has completed.
Isolate tests
Each test should start from a known state. Put shared setup in setUp, but avoid making one test depend on another.
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
setUp(() async {
await resetTestAccount();
});
testWidgets('shows an empty account', (tester) async {
app.main();
await tester.pumpAndSettle();
expect(find.text('No items yet'), findsOneWidget);
});
}Keep tests focused. A long test that covers login, checkout, settings, and logout is harder to diagnose than several smaller flows. If login is expensive, create a controlled authenticated state through test configuration instead of repeating unrelated UI steps in every test.
Diagnose failures systematically
When a test fails intermittently, record the exact step, device, operating system, and visible state. Then check these common causes:
| Symptom | Likely cause | Better approach |
|---|---|---|
| Finder finds zero widgets | UI has not settled | Pump after the state-changing action |
| Test hangs | Repeating animation or timer | Use bounded `pump` calls |
| Result changes between runs | Shared or live data | Reset state and use fixtures |
| Tap hits the wrong widget | Unstable selector | Add a semantic key |
| Failure occurs only on one device | Platform timing or layout difference | Test state, not pixel position |
Run a failing test repeatedly on the same device before changing the timeout. A larger timeout can hide a race instead of fixing it.
Exercise
Why is Future.delayed usually a weaker choice than pumpAndSettle or a bounded pump in an integration test?
Show answer
A fixed delay guesses the operation's duration. Pumping advances Flutter's frames and lets the test check a known UI state, while bounded pumping avoids hanging on repeating animations.