Sub topic 6
Making code testable with dependency injection
This chapter assumes you can write basic Dart with async and await. It also assumes you can build simple Flutter apps, add packages to pubspec.yaml, and write a basic unit test with test and expect. By the end you will be able to restructure a class so a test can replace its collaborators, and you will know the common ways this goes wrong.
Why hard-wired dependencies block testing
A dependency is any object that your class needs in order to do its job. Examples include an HTTP client, a database, a clock, or a random number generator. A class that creates its own dependencies is hard to test, because the test cannot choose what those dependencies do.
Here is a typical example.
import 'dart:convert';
import 'package:http/http.dart' as http;
class WeatherService {
Future<double> currentTemperature(String city) async {
final response = await http.get(
Uri.parse('https://api.example.com/weather?city=$city'),
);
final json = jsonDecode(response.body) as Map<String, dynamic>;
return (json['temp'] as num).toDouble();
}
}Testing this class means contacting a real server. The test would be slow and would fail when the network is down. It also gives you no way to check how the code behaves when the server returns an error, because you cannot make the server fail on demand.
The same problem appears with hidden dependencies such as DateTime.now(), Random(), or a global singleton. If the answer changes from run to run, the test cannot assert a fixed result.
What dependency injection means
Dependency injection (DI) means a class receives its dependencies from outside instead of creating them. The class declares what it needs. The caller decides what to provide.
In production, the caller passes real objects. In a test, the caller passes replacements. The class under test cannot tell the difference, so the test controls every input.
DI does not require a framework. In Dart, the most common form is plain constructor injection.
Step 1: Depend on an abstraction
If the constructor takes a concrete class such as http.Client, a test must either use that class or subclass it. Depending on an abstract interface is simpler. In Dart, every class defines an implicit interface, but an explicit abstract class states the contract clearly.
abstract class UserRepository {
Future<String> fetchName(int id);
}The interface lists only what the consumer needs. It should not mirror the whole API of the real implementation. A small interface is easier to fake and easier to understand.
Step 2: Inject through the constructor
The consumer takes the abstraction as a constructor parameter and stores it in a final field.
class Greeter {
Greeter(this.repository);
final UserRepository repository;
Future<String> greet(int id) async {
final name = await repository.fetchName(id);
return 'Hello, $name!';
}
}Greeter no longer knows whether names come from a server, a file, or a test. It knows only that something fulfils the UserRepository contract.
Step 3: Provide implementations
The real implementation lives in production code. A test provides its own.
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 user by name', () async {
final greeter = Greeter(FakeUserRepository());
expect(await greeter.greet(1), 'Hello, Ada!');
});
}No network is involved, and the test runs in milliseconds. The next chapter covers fakes and mocks in detail. Here the point is that the design made this test possible.
Injecting values you do not control
Some dependencies are not services. Time and randomness are the usual cases. You can inject them as functions.
import 'package:flutter_test/flutter_test.dart';
class TrialChecker {
TrialChecker({required this.start, DateTime Function()? now})
: _now = now ?? DateTime.now;
final DateTime start;
final DateTime Function() _now;
bool get isExpired => _now().difference(start).inDays >= 14;
}
void main() {
test('trial expires after 14 days', () {
final start = DateTime(2026, 1, 1);
final day13 = TrialChecker(start: start, now: () => DateTime(2026, 1, 14));
final day14 = TrialChecker(start: start, now: () => DateTime(2026, 1, 15));
expect(day13.isExpired, isFalse);
expect(day14.isExpired, isTrue);
});
}The optional parameter defaults to the real clock, so production callers write TrialChecker(start: start) and nothing changes for them. The test supplies a fixed time and gets a deterministic result. Without this seam, a test of the 14-day boundary would have to wait two weeks.
A default value keeps call sites short. Use this pattern for small, stable dependencies. For larger services, prefer a required parameter so that nobody forgets to wire them up.
Wiring objects together in the app
Constructor injection moves the question of who creates objects up to the caller. Eventually something must create the real objects. That place is called the composition root, and it is usually main().
void main() {
final repository = HttpUserRepository();
final greeter = Greeter(repository);
runApp(MyApp(greeter: greeter));
}Keep this wiring in one place. Business classes should not call HttpUserRepository() themselves. If they do, the seam is gone again.
Passing dependencies down the widget tree
Widgets can take dependencies as constructor parameters too.
import 'package:flutter/material.dart';
class GreetingPage extends StatelessWidget {
const GreetingPage({super.key, required this.greeter});
final Greeter greeter;
@override
Widget build(BuildContext context) {
return FutureBuilder<String>(
future: greeter.greet(1),
builder: (context, snapshot) {
return Text(snapshot.data ?? 'Loading...');
},
);
}
}This works for shallow trees. For deep trees, passing parameters through many layers becomes tedious. Packages such as provider or get_it solve that by exposing objects through the tree or a registry. They are conveniences on top of the same idea, and a later chapter shows how to override them in widget tests.
The call greeter.greet(1) inside build creates a new Future on every rebuild. That is a bug in production code, because each rebuild restarts the request. It is acceptable in a short example but not in a real app. Create the future once, for example in initState.
Common mistakes
| Mistake | Why it hurts | Fix |
|---|---|---|
| Creating the dependency inside the class | The test cannot replace it | Accept it in the constructor |
| Depending on a concrete class with many members | Fakes must reproduce a large API | Define a small abstract interface |
| Reading a global singleton inside methods | Tests share state and can affect each other | Inject the instance, or reset the global in `setUp` |
| Calling `DateTime.now()` directly in logic | Results change between runs | Inject a `DateTime Function()` |
| Injecting too many dependencies into one class | The class probably does too much | Split it into smaller classes |
| Creating real objects deep in the code | The composition root is no longer the only wiring place | Move construction to `main()` |
Trade-offs and limits
DI adds a little code. You write an interface, a constructor parameter, and a second implementation. This pays off when the dependency touches something slow, unpredictable, or external. It pays off less for simple pure logic. A function that adds two numbers needs no injection.
Do not abstract everything. Create an interface when a test needs to replace the dependency, or when you expect more than one implementation. Wrapping every class in an interface "just in case" adds noise.
A test double that is too different from the real thing can hide bugs. If FakeUserRepository always succeeds but the real one can throw, your tests never exercise the error path. Write fakes that can fail on request, and keep a few higher-level tests that use real components.
Summary of the technique
- Identify the dependency that makes the test slow, random, or external.
- Define a small abstract class describing what your code needs from it.
- Accept that abstraction through the constructor and store it in a
finalfield. - Create real objects in one place, the composition root.
- In tests, pass a fake or mock that you control.
Exercise
The class below reads the current time directly. Rewrite it so a test can fix the time, and say what default value keeps existing callers working. class Greeting { String message() { final hour = DateTime.now().hour; return hour < 12 ? 'Good morning' : 'Good afternoon'; } }
Show answer
Accept the clock as an optional constructor parameter that defaults to the real clock: class Greeting { Greeting({DateTime Function()? now}) : now = now ?? DateTime.now; final DateTime Function() now; String message() { return _now().hour < 12 ? 'Good morning' : 'Good afternoon'; } } The default is DateTime.now, so existing code that calls Greeting() behaves as before. A test passes now: () => DateTime(2026, 1, 1, 9) to get 'Good morning' and now: () => DateTime(2026, 1, 1, 15) to get 'Good afternoon'.
Exercise
Why does depending on a small abstract class make a fake easier to write than depending on the concrete HTTP implementation?
Show answer
A fake must provide every member of the type it replaces. A small abstract class lists only what the consumer needs, so the fake implements a few methods. A concrete HTTP class exposes a large API and may require real network setup, so replacing it takes more code and is more error prone.