Sub topic 1
Testing basics in Dart
Prerequisites
This chapter assumes you can write Dart classes and abstract interfaces, write a test with package:test, and read code that uses Future. You need a Dart or Flutter project to follow along.
Why dependencies make tests hard
A unit test checks one piece of code. Most real code calls other objects, such as a database or an HTTP client. Those objects can be slow, need a network, or return different data on each run. A test that uses them can fail for reasons unrelated to the code under test.
Dependency injection solves this. The class receives its collaborators through its constructor, so a test can pass in a substitute instead of the real object.
Fakes, stubs, and mocks
A test double is any stand-in object used in place of a real dependency. Three common kinds:
- A fake is a working but simplified implementation, such as an in-memory list used in place of a database.
- A stub returns fixed answers to calls and does not record them.
- A mock records how it was called, so the test can check those calls later.
mocktail creates mocks and lets you stub them.
Adding mocktail to your project
Add mocktail as a dev dependency so release builds do not include it:
flutter pub add dev:mocktailIn a pure Dart project, run dart pub add dev:mocktail instead.
Creating a mock class
Define an interface, then create a mock class that extends Mock and implements it:
import 'package:mocktail/mocktail.dart';
import 'package:test/test.dart';
abstract class UserRepository {
Future<String> fetchName(int id);
}
class MockUserRepository extends Mock implements UserRepository {}
void main() {
test('mock has the interface type', () {
final repo = MockUserRepository();
expect(repo, isA<UserRepository>());
});
}The mock has the interface type, so you can pass it to any code that expects a UserRepository. Later sections cover stubbing its methods and verifying its calls.
Exercise
Which kind of test double records how it was called so the test can check those calls later?
Show answer
A mock. A stub returns fixed answers without recording calls, and a fake is a simplified working implementation.