Sub topic 6
Making Code Testable with Dependency Injection
Prerequisites and the core idea
This chapter assumes that you know basic Dart classes, async and await, Flutter widgets, and how to run flutter test.
A class has a dependency when it needs another object to do its work. For example, a Greeter may need a repository to load a user's name. Dependency injection means giving that repository to Greeter from outside instead of creating it inside Greeter.
This separates two responsibilities:
Greeterdecides what to do with a name.- The application decides which repository supplies the name.
The separation makes tests faster and more predictable because a test can provide a fake repository.
Constructor injection
Constructor injection is usually the clearest form of dependency injection in Dart. The constructor receives the dependency and stores it in a field.
import 'package:flutter_test/flutter_test.dart';
abstract class UserRepository {
Future<String> fetchName(int id);
}
class Greeter {
Greeter(this.repository);
final UserRepository repository;
Future<String> greet(int id) async {
final name = await repository.fetchName(id);
return 'Hello, $name!';
}
}
class FakeUserRepository implements UserRepository {
@override
Future<String> fetchName(int id) async => 'Ada';
}
void main() {
test('greets the name returned by its repository', () async {
final greeter = Greeter(FakeUserRepository());
expect(await greeter.greet(1), 'Hello, Ada!');
});
}UserRepository is an abstract class. It describes the operation that Greeter needs without choosing a network client, database, or file system. FakeUserRepository is a hand-written test double. It returns known data without using a real service.
The application can construct the real object at its composition boundary:
final greeter = Greeter(RealUserRepository());A test constructs the same class with a fake:
final greeter = Greeter(FakeUserRepository());The Greeter class does not change between these environments.
Choosing an injection style
| Style | How it works | Best use |
|---|---|---|
| Constructor injection | A dependency is a required constructor argument | Required services and most application classes |
| Method injection | A dependency is passed to one method | A dependency used by only one operation |
| Setter or property injection | A dependency is assigned after construction | Optional configuration, used sparingly |
Constructor injection exposes required dependencies immediately. It also prevents an object from being used in an incomplete state. Avoid service locators and hidden global dependencies when possible. They make setup shorter but hide what a class needs and can make tests affect one another.
Common errors
A common mistake is injecting a concrete implementation instead of an abstraction:
class Greeter {
Greeter(this.repository);
final RealUserRepository repository;
}This prevents a simple fake from implementing a different behavior. Depend on UserRepository instead.
Another mistake is injecting too much. If a class receives a service locator, a whole application container, or ten unrelated services, its responsibilities may be mixed together. Split the class or define a smaller interface.
Keep production wiring near the application entry point. Keep tests responsible for constructing their own fakes or mocks. This makes each test's dependencies visible and avoids hidden setup.
Exercise
Why can a test replace the repository in Greeter without changing Greeter itself?
Show answer
Greeter depends on the UserRepository interface, so any object implementing that interface, including a fake, can be passed to its constructor.