Sub topic 3
Adding mocktail and creating your first mock
This chapter assumes you can write a basic flutter_test test and that you know Dart abstract classes and implements. It also assumes your classes receive their dependencies through constructors, which the previous chapter covered. By the end you will have mocktail installed, a working Mock class, and a clear picture of what that mock does and does not do on its own.
What mocktail is
mocktail is a Dart package for creating test doubles of your classes. A test double is an object that stands in for a real dependency during a test. mocktail's main feature is that it needs no code generation. You write a one-line class, and the package handles the rest at runtime.
This is the main difference from mockito. With mockito you annotate classes with @GenerateMocks, run build_runner, and import a generated file. With mocktail there is no annotation, no generated file and no build step. Tests run straight after you edit them, and the mock classes are ordinary Dart code you can read.
mocktail gets there by relying on null safety and a different calling style. Instead of passing a method call directly to when, you wrap it in a closure: when(() => repository.fetchUser('42')). The closure lets mocktail run the call in a controlled way and record which method and arguments you meant. Later chapters cover that in detail.
Adding the package
mocktail is only used by tests, so it belongs under dev_dependencies. From your project root, run:
flutter pub add --dev mocktailThis adds a line to pubspec.yaml and fetches the package. The result looks like this:
dev_dependencies:
flutter_test:
sdk: flutter
mocktail: ^1.0.0The exact version number on your machine may be newer. Keep the caret constraint that pub add writes for you.
You import the package in test files only:
import 'package:mocktail/mocktail.dart';For a pure Dart package with no Flutter dependency, the command is dart pub add --dev mocktail. The API is identical.
The code under test
The examples in this chapter use the same small set of classes as the rest of the tutorial. Put them in lib/user_repository.dart:
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}!';
}
}GreetingService depends on the UserRepository interface, not on a concrete class. In production you would pass an implementation that talks to a server or a database. In a test you pass a mock.
Creating your first mock
A mock class has two parts. It extends Mock, which supplies the recording and stubbing machinery. It also implements the type you want to replace, which makes the mock a valid value wherever that type is expected.
import 'package:mocktail/mocktail.dart';
import 'package:my_app/user_repository.dart';
class MockUserRepository extends Mock implements UserRepository {}The class body is empty. You do not write overrides for fetchUser, saveUser or watchUser. Dart requires a class that implements an interface to define every member, but Mock declares a noSuchMethod handler. When code calls a member the class does not define, Dart routes the call to noSuchMethod. mocktail uses that hook to record the call and look up any stubbed answer.
Replace my_app with the name: field from your own pubspec.yaml.
Where to put mock classes
Two layouts work well:
- Declare the mock at the top of the test file that uses it. This is the simplest choice and keeps the mock next to its tests.
- Move mocks used by several test files into a shared file such as
test/helpers/mocks.dart. Each test file imports it.
Keep mocks under test/, not lib/. They should never ship in your app, and mocktail is only a dev dependency, so importing it from lib/ would break your production build.
Name mocks MockX after the type they replace. The convention makes failure messages easy to read, because mocktail prints the mock's runtime type.
Using the mock in a test
The smallest useful test creates the mock and hands it to the class under test. The test below also stubs one method so that the service has something to call.
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:my_app/user_repository.dart';
class MockUserRepository extends Mock implements UserRepository {}
void main() {
test('a mock can be used wherever the interface is expected', () {
final repository = MockUserRepository();
expect(repository, isA<UserRepository>());
});
test('GreetingService uses the repository it is given', () async {
final repository = MockUserRepository();
when(() => repository.fetchUser('42'))
.thenAnswer((_) async => const User('42', 'Ada'));
final service = GreetingService(repository);
expect(await service.greet('42'), 'Hello, Ada!');
});
}Run it with flutter test. The first test only proves the mock satisfies the UserRepository type. The second shows the complete flow in miniature. You create the mock, teach it one answer with when(...).thenAnswer(...), inject it, and assert on the result. The next chapter explains when, thenReturn and thenThrow properly. For now, treat that line as "when fetchUser('42') is called, return a Future that completes with Ada".
The diagram shows what changed between production and the test. GreetingService never learns which implementation it received.
What a fresh mock does
A new mock has no behavior. It does not call the real code, because the real class's constructor is never run and its methods are never inherited. Every call is handled by noSuchMethod, which checks whether you stubbed that call.
If you did not stub the call, mocktail returns null. This matters when a method has a non-nullable return type. For example, fetchUser is declared to return Future<User>. If the service calls it on an unstubbed mock, the null cannot be converted to that type, and Dart throws an error similar to this:
type 'Null' is not a subtype of type 'Future<User>'That message almost always means "you forgot to stub this method". The fix is to add a when(...) for the call before the code under test runs.
Methods that return void or a nullable type behave less dramatically, since null is a valid result. This can hide a missing stub. A test may pass because an unstubbed void call silently did nothing, so use verify (covered later) when the call itself is part of the behavior you care about.
What you can and cannot mock
implements works on any class, not just abstract ones. You can write class MockHttpClient extends Mock implements http.Client {} and the mock will accept every call. There are limits worth knowing:
| Situation | What happens |
|---|---|
| Abstract class or interface | Works, and is the cleanest design. |
| Concrete class from your app | Works. The mock ignores the real implementation entirely. |
| Class from a package | Works if the class is not restricted by Dart 3 class modifiers. |
| `final`, `base` or `sealed` class declared in another library | Cannot be implemented, so the mock fails to compile. |
| Extension methods, static methods, top-level functions | Cannot be mocked, because calls bypass the instance. |
| Private members such as `_helper()` | Cannot be stubbed from a test, because the name is private to the library. |
If you need to replace something in the last three rows, wrap it in a small class of your own that exposes an instance method, and mock that wrapper. This is the same dependency-injection idea from the previous chapter, applied to code you do not control.
Mocks also cannot replace a class's constructor arguments or state. A MockUserRepository has no fields of its own. Anything it "knows" must come from stubs you set up.
Mocking generic and callback types
Generic interfaces work the same way. Supply the type arguments in the implements clause:
abstract class Cache<T> {
T? read(String key);
void write(String key, T value);
}
class MockUserCache extends Mock implements Cache<User> {}To mock a function rather than a class, define a small class with a call method and mock that. The mock can then be passed where a callback is expected, and you can verify how often it was invoked:
abstract class OnSaved {
void call(User user);
}
class MockOnSaved extends Mock implements OnSaved {}An instance of MockOnSaved is callable like a function, so onSaved(user) works, and it can be passed as a void Function(User) argument.
Common setup problems
Target of URI doesn't exist: 'package:mocktail/mocktail.dart': the package is not installed. Runflutter pub get, and check thatmocktailappears underdev_dependenciesand not at an incorrect indentation level.Missing concrete implementations: you wroteimplements UserRepositorybut forgotextends Mock. WithoutMock, nothing handles the missing members.The class 'X' can't be extended outside of its library: you wroteextends Mockcorrectly but tried to use a class restricted by a Dart 3 modifier. Mock a wrapper instead.- Mock imported from
lib/: if production code imports mocktail, the app build fails because the package is not available outside tests. Keep every mock undertest/. - Mixing up packages: both
mockitoandmocktailexportMock,whenandverify. Importing both into one file causes ambiguous-name errors. Pick one package per project.
Exercise
A teammate writes class MockUserRepository implements UserRepository {} and the compiler reports missing concrete implementations for fetchUser, saveUser and watchUser. What is missing, and why does adding it remove the error without writing any of those three methods?
Show answer
The class is missing extends Mock. Mock defines a noSuchMethod handler, and Dart sends calls to members the class does not declare to that handler. With it present, the compiler accepts the class even though it defines none of the interface's methods. The corrected line is class MockUserRepository extends Mock implements UserRepository {}.
Exercise
You create a MockUserRepository and pass it to GreetingService, then call service.greet('42') without stubbing anything. The test fails with type 'Null' is not a subtype of type 'Future<User>'. What caused it, and what do you add to fix it?
Show answer
An unstubbed call on a mock returns null. fetchUser is declared to return a non-nullable Future<User>, so Dart rejects the null. Before calling the service, stub the method, for example when(() => repository.fetchUser('42')).thenAnswer((_) async => const User('42', 'Ada'));.