Sub topic 11
Injecting Mocks into Widget Tests
Widget tests should test the UI separately from networks, databases, and other external systems. This chapter assumes you know Dart classes, Future, async and await, basic Flutter widgets, and the testWidgets and WidgetTester APIs.
A widget has a dependency when it needs another object to do work. For example, a profile page may need a UserRepository to load a user. Injecting a dependency means passing that object into the widget instead of creating it inside the widget. A test can then pass a mock repository.
Pass the dependency through the constructor
Constructor injection keeps the widget easy to understand and test. The widget does not need to know whether the repository uses HTTP, a database, or a mock.
The following example keeps the Future in the widget's state. This prevents a rebuild from starting a new repository request.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
class User {
const User(this.id, this.name);
final String id;
final String name;
}
abstract class UserRepository {
Future<User> fetchUser(String id);
}
class MockUserRepository extends Mock implements UserRepository {}
class ProfilePage extends StatefulWidget {
const ProfilePage({
super.key,
required this.repository,
required this.userId,
});
final UserRepository repository;
final String userId;
@override
State<ProfilePage> createState() => _ProfilePageState();
}
class _ProfilePageState extends State<ProfilePage> {
late final Future<User> _userFuture;
@override
void initState() {
super.initState();
_userFuture = widget.repository.fetchUser(widget.userId);
}
@override
Widget build(BuildContext context) {
return FutureBuilder<User>(
future: _userFuture,
builder: (context, snapshot) {
if (snapshot.hasError) {
return const Text('Something went wrong');
}
if (!snapshot.hasData) {
return const CircularProgressIndicator();
}
return Text(snapshot.data!.name);
},
);
}
}
void main() {
testWidgets('shows the user name after loading', (tester) async {
final repository = MockUserRepository();
when(() => repository.fetchUser('42'))
.thenAnswer((_) async => const User('42', 'Ada'));
await tester.pumpWidget(
MaterialApp(
home: ProfilePage(
repository: repository,
userId: '42',
),
),
);
expect(find.byType(CircularProgressIndicator), findsOneWidget);
await tester.pumpAndSettle();
expect(find.text('Ada'), findsOneWidget);
verify(() => repository.fetchUser('42')).called(1);
});
}pumpWidget builds the first frame. The stubbed Future has not completed at that point, so the loading indicator appears. pumpAndSettle pumps frames until scheduled work finishes. The test can then search for the loaded name.
Test loading, success, and failure states
A useful widget test checks behavior that users can see. For this page, those states include loading, successful loading, and an error.
To test the error state, change the stub:
when(() => repository.fetchUser('42'))
.thenThrow(Exception('offline'));
await tester.pumpWidget(
MaterialApp(
home: ProfilePage(repository: repository, userId: '42'),
),
);
await tester.pumpAndSettle();
expect(find.text('Something went wrong'), findsOneWidget);For asynchronous methods, use thenAnswer when the answer is a Future. thenThrow is useful for synchronous throws and also works for a method whose result is consumed by the widget. A Future that is deliberately delayed can help you test the loading state:
when(() => repository.fetchUser('42')).thenAnswer(
(_) async {
await Future<void>.delayed(const Duration(milliseconds: 50));
return const User('42', 'Ada');
},
);Avoid asserting only that the repository was called. Also assert the rendered result. Interaction verification checks the collaboration; widget assertions check what the user experiences.
> callout note > Prefer passing mocks through widget constructors. Global service locators and hidden static dependencies make tests harder to control and can allow one test's configuration to affect another.
Keep widget tests independent
Create a new mock inside each test or in setUp. Do not share a configured mock across tests. Shared stubs and recorded calls can make a test pass or fail because of another test.
Use verifyNever when a user action should prevent a request. Use verifyInOrder when the order of calls is part of the behavior. Keep these checks limited to meaningful interactions, because tests that verify every implementation detail are fragile.
Exercise
Why should a widget receive its repository through a constructor?
Show answer
Constructor injection lets the test provide a mock with controlled results, while production code can provide the real repository.