Sub topic 2
Designing code so dependencies can be replaced
A test can only swap out a dependency if the code under test accepts it from outside. This chapter covers how to structure Dart and Flutter code so that is possible. The next chapter uses that structure to create mocks.
This chapter assumes you know Dart classes, abstract classes and implicit interfaces, async/await, and how to write a basic flutter_test test. It also assumes you can pass arguments through a constructor. You don't need mocktail yet.
What a hard-wired dependency looks like
A dependency is any object your class needs to do its job: a repository, an HTTP client, a clock, a database. Code is hard to test when it creates those objects itself.
import 'package:http/http.dart' as http;
class HardWiredGreetingService {
// The service builds its own repository, and the repository builds
// a real network client. A test cannot replace either one.
final _repository = HttpUserRepository(
http.Client(),
baseUrl: Uri.parse('https://api.example.com/'),
);
Future<String> greet(String id) async {
final user = await _repository.fetchUser(id);
return 'Hello, ${user.name}!';
}
}Any test of greet now makes a real network call. The test is slow and fails when the network is down. It also can't force a timeout or a 500 response on demand. Nothing in the test can reach the private _repository field, so no mock can be placed there.
The fix is to move the decision about which repository to use out of the class and into the caller.
Constructor injection
Constructor injection means the class declares what it needs as constructor parameters and stores them in final fields. This is the technique the rest of the tutorial relies on.
class User {
const User(this.id, this.name);
final String id;
final String name;
}
abstract class UserRepository {
Future<User> fetchUser(String id);
Future<void> saveUser(User user);
Stream<User> watchUser(String id);
}
class GreetingService {
GreetingService(this._repository);
final UserRepository _repository;
Future<String> greet(String id) async {
final user = await _repository.fetchUser(id);
return 'Hello, ${user.name}!';
}
}Two things changed.
GreetingServiceno longer constructs anything. It receives aUserRepositoryand uses it.- The field type is
UserRepository, an abstract class, not the concreteHttpUserRepository. The service doesn't know or care what is behind the interface.
The second point matters as much as the first. If the parameter were typed as HttpUserRepository, a test double would have to be an HttpUserRepository too. Depending on the abstraction lets any class that implements UserRepository stand in.
Interfaces in Dart
Dart has no interface keyword. Every class defines an implicit interface, and implements makes another class promise to provide all its members. An abstract class is the usual way to declare the contract, because it signals that no one should instantiate it. Mocktail relies on this. A mock implements your interface, as the next chapter shows.
You can also depend on a concrete class and mock it, because implements works on any class. An explicit abstract interface is still the better default for three reasons. It documents exactly what the consumer needs. It keeps the production implementation free to change. It avoids mocking a class whose constructor or fields have side effects.
The production implementation
The real repository is also built with injection. It takes an http.Client rather than creating one, so its own tests could supply a fake client.
import 'dart:convert';
import 'package:http/http.dart' as http;
class HttpUserRepository implements UserRepository {
HttpUserRepository(this._client, {required this.baseUrl});
final http.Client _client;
/// Must end with a slash, for example https://api.example.com/
final Uri baseUrl;
@override
Future<User> fetchUser(String id) async {
final response = await _client.get(baseUrl.resolve('users/$id'));
if (response.statusCode != 200) {
throw Exception('Failed to load user $id (${response.statusCode})');
}
final json = jsonDecode(response.body) as Map<String, dynamic>;
return User(json['id'] as String, json['name'] as String);
}
@override
Future<void> saveUser(User user) async {
final response = await _client.put(
baseUrl.resolve('users/${user.id}'),
headers: {'content-type': 'application/json'},
body: jsonEncode({'id': user.id, 'name': user.name}),
);
if (response.statusCode >= 400) {
throw Exception('Failed to save user ${user.id}');
}
}
@override
Stream<User> watchUser(String id) async* {
while (true) {
yield await fetchUser(id);
await Future<void>.delayed(const Duration(seconds: 30));
}
}
}The dependencies form a chain: GreetingService needs a UserRepository, and HttpUserRepository needs an http.Client. Each class declares its needs at one level, and something above them assembles the chain.
The composition root
Someone has to create the real objects. Put that code in one place near the program's entry point, called the composition root. In a Flutter app this is usually main.
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() {
final client = http.Client();
final repository = HttpUserRepository(
client,
baseUrl: Uri.parse('https://api.example.com/'),
);
final greetingService = GreetingService(repository);
runApp(App(repository: repository, greetingService: greetingService));
}
class App extends StatelessWidget {
const App({
super.key,
required this.repository,
required this.greetingService,
});
final UserRepository repository;
final GreetingService greetingService;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: ProfilePage(repository: repository, userId: '42'),
);
}
}Only main mentions HttpUserRepository. Everything below it sees the interface. In a test there is no composition root, because the test builds the object it wants and passes in a double.
Injecting into widgets
Widgets follow the same rule. A widget that needs a repository declares it as a constructor parameter.
class ProfilePage extends StatelessWidget {
const ProfilePage({
super.key,
required this.repository,
required this.userId,
});
final UserRepository repository;
final String userId;
@override
Widget build(BuildContext context) {
return FutureBuilder<User>(
future: repository.fetchUser(userId),
builder: (context, snapshot) {
if (snapshot.hasError) return const Text('Something went wrong');
if (!snapshot.hasData) return const CircularProgressIndicator();
return Text(snapshot.data!.name);
},
);
}
}A widget test can now call tester.pumpWidget with a ProfilePage that holds a test double. Nothing global needs patching.
Passing a dependency through many layers of widgets gets tedious. Packages such as provider and get_it, and Flutter's own InheritedWidget, solve this by making the dependency available lower in the tree. They change how the object is delivered, not the principle. In tests you still supply a double at the point where the real object would be registered. Constructor injection works with no extra package, so the chapters that follow use it.
Other ways to receive a dependency
| Approach | How it works | Testability | Main drawback |
|---|---|---|---|
| Constructor injection | Parameters stored in final fields | High. Nothing hidden. | Long parameter lists in deep widget trees |
| Optional parameter with default | `Foo([Bar? bar]) : _bar = bar ?? RealBar()` | High, if tests pass the parameter | Production code can silently use the real object |
| Singleton or static access | `Api.instance.fetch()` | Low. Tests cannot replace the instance. | Hidden coupling and shared state across tests |
| Service locator (`get_it`) | Look up the object at runtime | Medium. Tests must register doubles and reset. | Missing registrations fail at runtime, not compile time |
| Creating it inside the method | `final c = http.Client();` | None | Every test touches the real object |
A default value is a reasonable compromise for small leaf classes. Use it with care: the parameter must stay optional, and the real implementation's constructor must be cheap and free of side effects, or tests will trigger them.
Edge cases and common mistakes
Static and top-level functions
You cannot replace a static method such as DateTime.now() or a top-level function. Wrap the call behind something injectable. For simple cases a function parameter is enough.
class SessionTimer {
SessionTimer({DateTime Function() now = DateTime.now})
: _now = now,
_start = now();
final DateTime Function() _now;
final DateTime _start;
Duration get elapsed => _now().difference(_start);
}Production code calls SessionTimer() and gets the real clock. A test passes now: () => fixedTime and controls time without any mocking library.
Work in constructors
If a constructor starts a network call or opens a file, a test that only wants to construct the object triggers that work. Keep constructors to storing fields. Start work in a method such as load() that the test calls on purpose.
Interfaces that are too wide
If GreetingService only calls fetchUser, but the interface has fifteen members, every test double must deal with fifteen members. Split large interfaces by what each consumer needs. Small interfaces also make stubs shorter.
Creating dependencies in `build` or `initState`
Writing ProfilePage(repository: HttpUserRepository(...)) inside another widget's build method brings back the original problem one level up. The widget cannot be tested without the network, and it creates a new repository on every rebuild. Create the object once at the composition root, or in a long-lived owner, and pass it down.
Exposing internals only for tests
Don't make a private field public or add a setter such as set repositoryForTesting just to get a double in. If the class needs the dependency, it belongs in the constructor.
What you can do next
Your code now has a seam: a constructor parameter, typed as an interface, where a test can plug in a different implementation. The next chapter adds mocktail and creates MockUserRepository to fill that seam.
Exercise
A class ReportExporter contains the line final _storage = FileStorage(); and calls _storage.write(path, data) in its export method. Describe the changes needed so a test can replace the storage, and say where the real FileStorage should be created.
Show answer
Declare an abstract class (for example Storage) with the write method, and make FileStorage implement it. Change ReportExporter to take a Storage in its constructor and store it in a final field typed as Storage, not FileStorage. Remove the FileStorage() construction from the class. Create the real FileStorage once at the composition root (usually main) and pass it to ReportExporter. A test then passes a test double that implements Storage.
Exercise
Why is Foo({Bar? bar}) : _bar = bar ?? RealBar() usually acceptable, while a class that reads Api.instance from a static field is not?
Show answer
The optional parameter gives tests a seam: they pass their own Bar and the default is never used. The static Api.instance has no seam. The class reaches for a global object that tests cannot replace, and any state in that object persists across tests. The default-parameter form is only safe if RealBar() has no side effects when constructed.