Sub topic 1
Why Mock Dependencies in Tests
Prerequisites
This chapter assumes that you know Dart classes, abstract classes, constructors, Future, and basic Flutter tests with flutter_test. You should also understand dependency injection, which means passing a class's collaborators into its constructor instead of creating them inside the class.
A dependency is an object that another object needs to do its work. A user service might depend on a repository. A repository might depend on an HTTP client. In production, these dependencies connect to databases, web services, files, or device APIs.
Testing the service together with all of those systems makes a test slow and unpredictable. A mock is a test object that replaces a dependency and lets the test control its behavior.
Isolation makes tests useful
Suppose GreetingService asks a repository for a user:
class User {
const User(this.id, this.name);
final String id;
final String name;
}
abstract class UserRepository {
Future<User> fetchUser(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}!';
}
}GreetingService should be tested as a unit. The test should answer questions about the service:
- Does it request the correct user?
- Does it format the greeting correctly?
- What does it do when the repository reports an error?
The test does not need to check whether the HTTP client can reach a server. That is a different responsibility and should have separate tests.
A mock repository can return a known user every time. It can also throw a controlled error. The test then has the same input on every run, so a failure points more clearly to the service rather than to a network connection or database.
Speed and determinism
A real dependency often introduces delays and failure conditions:
- A network request can take seconds or fail because the device is offline.
- A database can contain data left by another test.
- The current time can change the result.
- A file system can differ between development machines.
- A payment or messaging service can cause unwanted side effects.
A mock avoids these boundaries. It returns values held in memory, so a unit test usually runs in milliseconds. The test can also exercise cases that are difficult to produce with a real system, such as a timeout or a malformed response.
| Dependency in the test | Typical result |
|---|---|
| Real HTTP client | Slow, network-dependent, harder to repeat |
| Mock HTTP client | Fast, controlled response, predictable |
| In-memory fake repository | Fast, realistic state behavior |
| Real database | Broad integration coverage, more setup |
Isolation does not mean that real dependencies should never be tested. It means that each test has a clear scope. Unit tests check one unit quickly. Integration tests check that multiple real parts work together. Both kinds provide useful information.
Designing for replacement
A class is easier to isolate when it depends on an interface rather than a concrete implementation. In Dart, an abstract class commonly provides that interface:
class ApiUserRepository implements UserRepository {
ApiUserRepository(this.client);
final HttpClient client;
@override
Future<User> fetchUser(String id) async {
// Production HTTP request would happen here.
throw UnimplementedError();
}
}GreetingService knows only about UserRepository. It does not know whether the repository uses HTTP, a database, a mock, or an in-memory fake. This design is dependency injection: the caller supplies the dependency.
Constructor injection is usually the simplest form because the dependency is visible and required:
final service = GreetingService(repository);When production code supplies ApiUserRepository and a test supplies a mock, the service remains unchanged. This separation keeps tests focused and makes the production design easier to replace when requirements change.
Exercise
Why is a mock repository useful when testing GreetingService, and what does it fail to test?
Show answer
It provides fast, predictable users or errors so the test can focus on GreetingService. It does not test the real repository's network or database behavior.