mockito
Mockito Skill
This skill defines how to correctly use the mockito package for mocking in Dart and Flutter tests.
1. Mock vs. Fake vs. Real Object
| Use | When |
|---|---|
| Real object | Prefer over mocks when practical. |
Fake (extends Fake) |
Lightweight custom implementation; override only the methods you need. Prefer over mocks when you don't need interaction verification. |
Mock (extends Mock) |
Only when you need to verify interactions (call counts, arguments) or stub dynamic responses. |
- Data models should not be mocked if they can be constructed with stubbed data.
- Only use mocks if your test has
verifyassertions; otherwise prefer real or fake objects.
2. Generating Mocks
([MyClass])
// or for nice mocks (return simple legal values for missing stubs):
([MockSpec<MyClass>()])
void main() { ... }
dart run build_runner build
- Only annotate files under
test/for mock generation by default. - Use a
build.yamlif you need to generate mocks outside oftest/. - Never add
@overridemethods or implementations to a class extendingMock. - Never stub responses in a mock's constructor or inside the mock class — always stub in your tests.
3. Stubbing
final mock = MockCat();
// Return a value
when(mock.sound()).thenReturn('Meow');
// Throw an error
when(mock.sound()).thenThrow(Exception('No sound'));
// Calculate response at call time
when(mock.sound()).thenAnswer((_) => computedValue);
// Return values in sequence
when(mock.sound()).thenReturnInOrder(['Meow', 'Purr']);
- Always stub methods/getters before using them if you need specific return values.
- Missing stub behavior:
@GenerateMocks→ throws;@GenerateNiceMocks→ returns a simple legal value. - Use
throwOnMissingStub(mock)to throw on any unstubbed call.
4. Verification
verify(mock.sound()); // called at least once
verifyNever(mock.eat(any)); // never called
verify(mock.sound()).called(2); // called exactly twice
Async:
await untilCalled(mock.sound()); // wait for the interaction
5. Argument Matchers
// Flexible stubbing
when(mock.eat(any)).thenReturn(true);
when(mock.eat(argThat(isNotNull))).thenReturn(true);
// Named arguments
when(mock.fetch(any, headers: any)).thenReturn(response);
- Do not use
nullas an argument adjacent to an argument matcher. - For named arguments, use
anyorargThatas values, not as argument names.
6. Capturing Arguments
final captured = verify(mock.eat(captureAny)).captured;
print(captured.last); // last captured argument
Use captureThat for conditional capturing.
7. Resetting Mocks
reset(mock); // clear all stubs AND interactions
clearInteractions(mock); // clear only recorded interactions
8. Mocking Function Types
To mock a function type (e.g., a callback), define an abstract class with the required signature and generate mocks for it:
abstract class Callback {
void call(String value);
}
([Callback])
9. Debugging
logInvocations([mock1, mock2]); // print all collected invocations
References
More from evanca/flutter-ai-rules
riverpod
Uses Riverpod for state management in Flutter/Dart. Use when setting up providers, combining requests, managing state disposal, passing arguments, performing side effects, testing providers, or applying Riverpod best practices.
28bloc
Implement Flutter state management using the bloc and flutter_bloc libraries. Use when creating a new Cubit or Bloc, modeling state with sealed classes or status enums, wiring BlocBuilder/BlocListener/BlocProvider in widgets, writing bloc unit tests, refactoring state management, or deciding between Cubit and Bloc.
21effective-dart
Apply Effective Dart guidelines to write idiomatic, high-quality Dart and Flutter code. Use when writing new Dart code, reviewing pull requests for style compliance, refactoring naming conventions, adding doc comments, structuring imports, enforcing type annotations, or running code review checks against Effective Dart standards.
20flutter-app-architecture
Implement layered Flutter app architecture with MVVM, repositories, services, and dependency injection. Use when scaffolding a new Flutter project, refactoring an existing app into layers, creating view models and repositories, configuring dependency injection, implementing unidirectional data flow, or adding a domain layer for complex business logic.
18testing
Write, review, and improve Flutter and Dart tests including unit tests, widget tests, and golden tests. Use when writing new tests, reviewing test quality, fixing flaky tests, adding test coverage, structuring test files, or choosing between unit and widget tests.
16architecture-feature-first
Structure Flutter apps using layered architecture (UI / Logic / Data) with feature-first file organization. Use when creating new features, designing the project folder structure, adding repositories, services, view models (or cubits/providers/notifiers), wiring dependency injection, or deciding which layer owns a piece of logic. State management agnostic.
16