Sub topic 2
Designing Code So Dependencies Can Be Replaced
Assume you know Dart classes, abstract classes, Future, basic tests, and Flutter's testWidgets workflow. This chapter focuses on dependency injection, which is the design step that makes mocking possible.
What dependency injection solves
A dependency is an object that another object needs to do its work. For example, a profile service might need a user repository to load a user from an API or database.
If the service creates the repository itself, the service is tightly coupled to one implementation:
class ProfileService {
Future<String> greeting(String id) async {
final repository = ApiUserRepository();
final user = await repository.fetchUser(id);
return 'Hello, ${user.name}!';
}
}This code is difficult to test. Every test uses the real API repository unless you change the service itself. Tests may be slow, require a network connection, and produce different results when the server changes.
Dependency injection means giving an object the dependencies it needs from outside. The service does not decide which repository to construct. The caller supplies one.
Define an interface at the boundary
An abstract class defines the operations that the service needs. It hides whether the data comes from an API, a database, memory, or a mock.
class User {
const User(this.id, this.name);
final String id;
final String name;
}
abstract class UserRepository {
Future<User> fetchUser(String id);
}
class ProfileService {
ProfileService({required UserRepository repository})
: _repository = repository;
final UserRepository _repository;
Future<String> greeting(String id) async {
final user = await _repository.fetchUser(id);
return 'Hello, ${user.name}!';
}
}
class InMemoryUserRepository implements UserRepository {
@override
Future<User> fetchUser(String id) async {
return const User('42', 'Ada');
}
}
Future<void> main() async {
final service = ProfileService(
repository: InMemoryUserRepository(),
);
print(await service.greeting('42'));
}ProfileService depends on the UserRepository interface rather than InMemoryUserRepository. The constructor stores the supplied object in _repository.
A concrete class implements the interface by providing the required methods. In production, the application can supply an API implementation. In a test, it can supply a mock or a small fake.
Choose the injection point
Constructor injection is usually the clearest choice in Dart. It makes required dependencies visible and prevents the service from existing in an unusable state.
| Injection style | Best use | Main concern |
|---|---|---|
| Constructor | Required dependencies | Callers must provide them |
| Method parameter | A dependency used by one operation | Parameters can become noisy |
| Service locator | Large legacy applications | Dependencies become hidden |
Avoid global variables and service locators for ordinary dependencies. They hide where an object gets its collaborators and make tests depend on shared application state.
Replace the dependency in a test
A test double is an object used instead of a real dependency. A mock records calls and can return configured values. A fake provides a lightweight working implementation. With constructor injection, either can be passed directly to ProfileService.
The service should be tested through its public behavior:
class FakeUserRepository implements UserRepository {
FakeUserRepository(this.user);
final User user;
String? requestedId;
@override
Future<User> fetchUser(String id) async {
requestedId = id;
return user;
}
}
Future<void> exampleTest() async {
final repository = FakeUserRepository(
const User('7', 'Grace'),
);
final service = ProfileService(repository: repository);
final result = await service.greeting('7');
assert(result == 'Hello, Grace!');
assert(repository.requestedId == '7');
}Later, MockUserRepository can replace this fake. The ProfileService code does not change because both objects satisfy UserRepository.
Apply the same design to widgets
A widget can receive a repository through its constructor and pass it to a service or use it directly. A widget test then supplies a controlled dependency instead of configuring a real network client.
Prefer required named parameters for dependencies:
class ProfilePage extends StatelessWidget {
const ProfilePage({
super.key,
required this.repository,
});
final UserRepository repository;
@override
Widget build(BuildContext context) {
return FutureBuilder<User>(
future: repository.fetchUser('42'),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return const CircularProgressIndicator();
}
return Text(snapshot.data!.name);
},
);
}
}This design keeps the widget reusable and lets a widget test inject a mock repository with predictable data.
Exercise
Why is ProfileService(repository: repository) easier to test than a service that calls ApiUserRepository() inside greeting()?
Show answer
The test can supply a mock or fake repository, so it controls returned data and errors without changing the service or contacting a real API.