Sub topic 11
Testing widgets that depend on services
This chapter assumes you can write a basic testWidgets test, use finders, and call pump. You should also know how constructor injection and fakes or mocks work from the earlier chapters.
Why widgets need special handling
A widget that calls a repository, an API client, or a database during build or initState is hard to test. Under flutter test, a real HTTP client does not reach a server. The test environment blocks it and returns status 400. A real database or platform plugin has no host platform to talk to.
The fix is the one you already used for plain classes. The widget receives its service from outside, and the test passes a replacement. What changes is timing. A widget goes through frames, so you must decide when the replacement answers and how many frames you pump to see the result.
A widget with an injected service
ProfilePage loads a user name once, shows a spinner while waiting, and shows an error message if loading fails. It takes a UserRepository through its constructor and starts the request in initState, so rebuilds do not trigger new requests.
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
abstract class UserRepository {
Future<String> fetchName(int id);
}
class ProfilePage extends StatefulWidget {
const ProfilePage({
super.key,
required this.repository,
required this.userId,
});
final UserRepository repository;
final int userId;
@override
State<ProfilePage> createState() => _ProfilePageState();
}
class _ProfilePageState extends State<ProfilePage> {
late final Future<String> _name;
@override
void initState() {
super.initState();
_name = widget.repository.fetchName(widget.userId);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: FutureBuilder<String>(
future: _name,
builder: (context, snapshot) {
if (snapshot.hasError) {
return const Text('Could not load user');
}
if (snapshot.hasData) {
return Text(snapshot.data!);
}
return const CircularProgressIndicator();
},
),
),
);
}
}
class ControllableUserRepository implements UserRepository {
final completer = Completer<String>();
int calls = 0;
@override
Future<String> fetchName(int id) {
calls++;
return completer.future;
}
}
class MockUserRepository extends Mock implements UserRepository {}
Widget buildPage(UserRepository repository) {
return MaterialApp(
home: ProfilePage(repository: repository, userId: 1),
);
}
void main() {
testWidgets('shows a spinner, then the name', (tester) async {
final repository = ControllableUserRepository();
await tester.pumpWidget(buildPage(repository));
expect(find.byType(CircularProgressIndicator), findsOneWidget);
expect(find.text('Ada'), findsNothing);
repository.completer.complete('Ada');
await tester.pump();
expect(find.byType(CircularProgressIndicator), findsNothing);
expect(find.text('Ada'), findsOneWidget);
expect(repository.calls, 1);
});
testWidgets('shows an error message when loading fails', (tester) async {
final repository = ControllableUserRepository();
await tester.pumpWidget(buildPage(repository));
repository.completer.completeError(Exception('offline'));
await tester.pump();
expect(find.text('Could not load user'), findsOneWidget);
});
testWidgets('asks the repository for the right user', (tester) async {
final repository = MockUserRepository();
when(() => repository.fetchName(1)).thenAnswer((_) async => 'Ada');
await tester.pumpWidget(buildPage(repository));
await tester.pump();
expect(find.text('Ada'), findsOneWidget);
verify(() => repository.fetchName(1)).called(1);
});
}Run it with flutter test. The file needs mocktail under dev_dependencies in pubspec.yaml.
Controlling when the service answers
The first two tests use a hand-written fake backed by a Completer. A Completer is an object that creates a Future and lets the test decide when and how it finishes. That gives you a deterministic sequence:
pumpWidgetbuilds the first frame. The future is pending, so the spinner is on screen.- The test completes the future with a value or an error.
pumpruns one more frame, andFutureBuilderrebuilds with the result.
This is the main advantage over thenAnswer((_) async => 'Ada'). A mock that answers immediately skips the loading state, so you cannot assert on it. Use a Completer whenever the intermediate state matters.
The third test uses a mocktail mock. It is shorter when you only care about the final result and about which arguments the widget passed. The await tester.pump() after pumpWidget gives the already completed future one frame to deliver its value to FutureBuilder.
Choosing between a fake and a mock
| Situation | Better choice | Reason |
|---|---|---|
| You need to assert the loading state | Fake with a `Completer` | The test controls timing |
| Several tests share the same canned data | Fake | One class, no repeated stubbing |
| You need to check call count or arguments | Mock with `verify` | Built-in call tracking |
| One test needs an unusual answer | Mock with `when` | No new class |
| The service has many methods and the widget uses one | Mock | You stub only what is called |
You can combine them. A fake can count its own calls, as ControllableUserRepository does with calls.
Providing services other than through the constructor
Many apps inject services through a package such as Provider, Riverpod, or get_it, or through an InheritedWidget. The testing principle is the same: the test supplies the replacement at the same place where main supplies the real one.
- With constructor injection, pass the fake to the widget, as above.
- With a scope widget such as Provider or Riverpod, wrap the widget under test in that scope inside
pumpWidget. Override the real service with the fake there. - With a service locator such as get_it, register the fake before
pumpWidgetand reset the locator intearDown.
Whichever approach you use, the widget under test usually needs ancestors that the real app provides: MaterialApp for theming, text direction, and navigation, and sometimes Localizations or a MediaQuery override. Put them in one helper such as buildPage so every test starts from the same setup.
Common errors
pumpAndSettle times out. It keeps pumping frames until none are scheduled. A CircularProgressIndicator schedules a new frame on every tick, so pumpAndSettle waits forever while the spinner is visible and then throws a timeout. If your fake never completes, this is the likely cause. Complete the future first, or use pump with an explicit duration.
The spinner never disappears. You completed the future but did not pump. State changes reach the screen only on the next frame, so call await tester.pump() after completing it.
Real network or plugin calls fail. A MissingPluginException, or HTTP status 400 from a test that never meant to call the network, means a real service reached the widget. Check that every route into the widget goes through the injected dependency, including child widgets that create their own clients.
registerFallbackValue error from mocktail. Matchers such as any() need a fallback value for argument types that mocktail cannot construct. With int or String this is not needed. For your own classes, call registerFallbackValue(MyArgument()) in setUpAll.
Stubbing a method that returns a Future with thenReturn. For async methods, use thenAnswer((_) async => value). Using thenReturn with a plain value fails the type check, and a mock with no stub returns null, which throws when the widget awaits it.
Starting the request in build. If the widget calls fetchName inside build, each rebuild calls the service again. In a test this appears as verify(...).called(1) failing with a higher count after you pump twice. Start the request in initState, or in a state-management object, as ProfilePage does.
Checking interactions
Verifying calls is useful when the widget triggers an action, such as a save button. After tapping, assert on the service:
verify(() => repository.save(any())).called(1);Check what the user would see first, and verify calls second. A test that only verifies calls can pass while the screen shows the wrong thing. Use verifyNever for cases such as an invalid form, where the service must not be called at all.
Exercise
A widget test completes a Completer held by a fake repository and then calls await tester.pumpAndSettle(). The widget shows a CircularProgressIndicator until the data arrives. The test sometimes passes, but another test that never completes its Completer fails with a timeout. Why does the second test time out, and how would you fix it?
Show answer
The spinner is visible and animating in the second test, so it schedules a new frame on every tick. pumpAndSettle waits until no frames are scheduled, so it never settles and times out. In the first test the future completes, the spinner leaves the tree, and the frames stop. The fix is to complete the Completer before calling pumpAndSettle. If the test is meant to check the loading state, use await tester.pump() instead and assert that the spinner is present.
Exercise
You want a widget test to prove that ProfilePage calls fetchName exactly once even if the parent rebuilds it with pumpWidget a second time using the same repository and userId. What happens in the test with the code in this chapter, and why?
Show answer
Calling pumpWidget again with a widget of the same type and key updates the existing element instead of creating a new state. Flutter keeps the same _ProfilePageState, so initState does not run again and fetchName stays at one call. You can assert this with expect(repository.calls, 1) on the fake, or verify(() => repository.fetchName(1)).called(1) on the mock. If the request were made in build, the count would grow with each rebuild.