mockito
5.8.1, released 3 months ago by dart.dev
A mock framework inspired by Mockito with APIs for Fakes, Mocks, behavior verification, and stubbing.
WASM-readyRock solid
What it does
Provides APIs to create mock and fake classes for testing Dart and Flutter applications. It supports behavior verification, method stubbing, argument matchers, and code generation for null-safe classes.
AI-written summary of version 5.8.1, based on the package's README and metadata. Report an inaccuracy
Use it when
- You need to test classes that depend on external services or complex dependencies.
- You want to verify interactions, arguments, and call orders on mocked objects.
Skip it when
- You can easily construct real instances or tested fake implementations for your tests.
- You prefer runtime-only mocking libraries that do not require build_runner.
Strengths
- Robust behavior verification and stubbing features.
- Supports null safety and generates nice mocks to avoid runtime type exceptions.
Weaknesses
- Requires running build_runner for code generation.
- Has an awkward syntax requirement for naming arguments within argument matchers.
Setup
- Kind
- Pure Dart
- Effort
- Medium
- Code generation
- Yes (build_runner)
- Direct dependencies
- 10
Add build_runner to dev_dependencies and run `dart run build_runner build` to generate mock classes.
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
@GenerateNiceMocks([MockSpec<Cat>()])
import 'cat_test.mocks.dart';
class Cat {
String sound() => "Meow";
}
void main() {
var cat = MockCat();
when(cat.sound()).thenReturn("Purr");
expect(cat.sound(), "Purr");
}Alternatives
Packages that do the same job and could replace mockito.
Works with
Packages commonly used together with mockito: ones it builds on, ones built on it, and its own family.
- analyzermockito depends on itPerforms static analysis of Dart code for tool integration and embedding.
- dart_stylemockito depends on itProvides an API and CLI to format Dart source code automatically.
- test_apimockito depends on itThe user facing API for structuring Dart tests and checking expectations.
- matchermockito depends on itSupport for specifying test expectations via an extensible Matcher class.
- code_buildermockito depends on itA fluent, builder-based library for generating valid Dart code programmatically.
- buildmockito depends on itPackage for authoring build_runner compatible code generators.
- source_genmockito depends on itSource code generation builders and utilities for the Dart build system.
- build_runnerUsed togetherA build system for Dart code generation and modular compilation.