mockito 2.2.3

  • Installing
  • Versions
  • 97

Mock library for Dart inspired by Mockito.

Pub Build Status

Current mock libraries suffer from specifying method names as strings, which cause a lot of problems:

  • Poor refactoring support: rename method and you need manually search/replace it's usage in when/verify clauses.
  • Poor support from IDE: no code-completion, no hints on argument types, can't jump to definition

Dart's mockito package fixes these issues - stubbing and verifying are first-class citizens.

Let's create mocks

import 'package:mockito/mockito.dart';

// Real class
class Cat {
  String sound() => "Meow";
  bool eatFood(String food, {bool hungry}) => true;
  int walk(List<String> places);
  void sleep() {}
  void hunt(String place, String prey) {}
  int lives = 9;

// Mock class
class MockCat extends Mock implements Cat {}

// mock creation
var cat = new MockCat();

Let's verify some behaviour!

//using mock object
//verify interaction

Once created, mock will remember all interactions. Then you can selectively verify whatever interaction you are interested in.

How about some stubbing?

// Unstubbed methods return null:
expect(cat.sound(), nullValue);

// Stubbing - before execution:
expect(cat.sound(), "Purr");

// You can call it again:
expect(cat.sound(), "Purr");

// Let's change the stub:
expect(cat.sound(), "Meow");

// You can stub getters:
expect(cat.lives, 9);

// You can stub a method to throw:
when(cat.lives).thenThrow(new RangeError('Boo'));
expect(() => cat.lives, throwsRangeError);

// We can calculate a response at call time:
var responses = ["Purr", "Meow"];
when(cat.sound()).thenAnswer(() => responses.removeAt(0));
expect(cat.sound(), "Purr");
expect(cat.sound(), "Meow");

By default, for all methods that return a value, mock returns null. Stubbing can be overridden: for example common stubbing can go to fixture setup but the test methods can override it. Please note that overridding stubbing is a potential code smell that points out too much stubbing. Once stubbed, the method will always return stubbed value regardless of how many times it is called. Last stubbing is more important, when you stubbed the same method with the same arguments many times. In other words: the order of stubbing matters, but it is meaningful rarely, e.g. when stubbing exactly the same method calls or sometimes when argument matchers are used, etc.

Argument matchers

// You can use arguments itself:

// ... or collections:

// ... or matchers:

// ... or mix aguments with matchers:
when(cat.eatFood(argThat(startsWith("dry")), true).thenReturn(true);
expect(cat.eatFood("fish"), isTrue);
expect(cat.walk(["roof","tree"]), equals(2));
expect(cat.eatFood("dry food"), isFalse);
expect(cat.eatFood("dry food", hungry: true), isTrue);

// You can also verify using an argument matcher:

// You can verify setters:
cat.lives = 9;

If an argument other than an ArgMatcher (like any, anyNamed(), argThat, captureArg, etc.) is passed to a mock method, then the equals matcher is used for argument matching. If you need more strict matching consider use argThat(identical(arg)).

Verifying exact number of invocations / at least x / never


// Exact number of invocations:

// Or using matcher:

// Or never called:

Verification in order


Verification in order is flexible - you don't have to verify all interactions one-by-one but only those that you are interested in testing in order.

Making sure interaction(s) never happened on mock


Finding redundant invocations


Capturing arguments for further assertions

// Simple capture:
expect(verify(cat.eatFood(captureAny)).captured.single, "Fish");

// Capture multiple calls:
expect(verify(cat.eatFood(captureAny)).captured, ["Milk", "Fish"]);

// Conditional capture:
expect(verify(cat.eatFood(captureThat(startsWith("F")).captured, ["Fish"]);

Waiting for an interaction

// Waiting for a call:
await untilCalled(cat.chew()); //completes when cat.chew() is called

// Waiting for a call that has already happened:
await untilCalled(cat.eatFood(any)); //will complete immediately

Resetting mocks

// Clearing collected interactions:

// Resetting stubs and collected interactions:
expect(cat.eatFood("Fish"), false);


// Spy creation:
var cat = spy(new MockCat(), new Cat());

// Stubbing - before execution:

// Using mocked interaction:
expect(cat.sound(), "Purr");

// Using a real object:
expect(cat.lives, 9);


// Print all collected invocations of any mock methods of a list of mock objects:
logInvocations([catOne, catTwo]);

// Throw every time that a mock method is called without a stub being matched:

Strong mode compliance

Unfortunately, the use of the arg matchers in mock method calls (like cat.eatFood(any)) violates the Strong mode type system. Specifically, if the method signature of a mocked method has a parameter with a parameterized type (like List<int>), then passing any or argThat will result in a Strong mode warning:

[warning] Unsound implicit cast from dynamic to List<int>

In order to write Strong mode-compliant tests with Mockito, you might need to use typed, annotating it with a type parameter comment. Let's use a slightly different Cat class to show some examples:

class Cat {
  bool eatFood(List<String> foods, [List<String> mixins]) => true;
  int walk(List<String> places, {Map<String, String> gaits}) => 0;

class MockCat extends Mock implements Cat {}

var cat = new MockCat();

OK, what if we try to stub using any:


Let's analyze this code:

$ dartanalyzer --strong test/cat_test.dart
Analyzing [lib/cat_test.dart]...
[warning] Unsound implicit cast from dynamic to List<String> (test/cat_test.dart, line 12, col 20)
1 warning found.

This code is not Strong mode-compliant. Let's change it to use typed:

$ dartanalyzer --strong test/cat_test.dart
Analyzing [lib/cat_test.dart]...
No issues found

Great! A little ugly, but it works. Here are some more examples:

when(cat.eatFood(typed(any), typed(any))).thenReturn(true);

Named args require one more component: typed needs to know what named argument it is being passed into:

when(cat.walk(typed(any), gaits: typed(any, named: 'gaits')))

Note the named argument. Mockito should fail gracefully if you forget to name a typed call passed in as a named argument, or name the argument incorrectly.

One more note about the typed API: you cannot mix typed arguments with null arguments:

when(cat.eatFood(null, typed(any))).thenReturn(true); // Throws!
    typed(any))).thenReturn(true); // Works.

How it works

The basics of the Mock class are nothing special: It uses noSuchMethod to catch all method invocations, and returns the value that you have configured beforehand with when() calls.

The implementation of when() is a bit more tricky. Take this example:

// Unstubbed methods return null:
expect(cat.sound(), nullValue);

// Stubbing - before execution:

Since cat.sound() returns null, how can the when() call configure it?

It works, because when is not a function, but a top level getter that returns a function. Before returning the function, it sets a flag (_whenInProgress), so that all Mock objects know to return a "matcher" (internally _WhenCall) instead of the expected value. As soon as the function has been invoked _whenInProgress is set back to false and Mock objects behave as normal.

Be careful never to write when; (without the function call) anywhere. This would set _whenInProgress to true, and the next mock invocation will return an unexpected value.

The same goes for "chaining" mock objects in a test call. This will fail:

var mockUtils = new MockUtils();
var mockStringUtils = new MockStringUtils();

// Setting up mockUtils.stringUtils to return a mock StringUtils implementation

// Some tests

// Instead use this:

This fails, because verify sets an internal flag, so mock objects don't return their mocked values anymore but their matchers. So mockUtils.stringUtils will not return the mocked stringUtils object you put inside.

You can look at the when and Mock.noSuchMethod implementations to see how it's done. It's very straightforward.

NOTE: This is not an official Google product


  • Avoid generlized void isses. Fixes Mockito's compliance with Dart SDK 2.0.0-dev.23.0.


  • Remove last violation of USES_DYNAMIC_AS_BOTTOM error. This should make Mockito compatible with Dart 2 semantics.


  • Internal fixes only (stop using comment-based generic method syntax).


  • Add new feature to wait for an interaction: untilCalled. See the README for documentation.


  • Add documentation for when, verify, verifyNever, resetMockitoState.
  • Expose throwOnMissingStub, resetMockitoState.
  • Improve failure message for verify.
  • SDK version ceiling bumped to <2.0.0-dev.infinity to support Dart 2.0 development testing.
  • Add a Mockito + test package example at test/example/iss.


  • Start using the new InvocationMatcher instead of the old matcher.
  • Change throwOnMissingStub back to invoking Object.noSuchMethod:
    • It was never documented what the thrown type should be expected as.
    • You can now just rely on throwsNoSuchMethodError if you want to catch it.


  • Add a new throwOnMissingStub method to the API.


  • Removed mockito_no_mirrors.dart


  • Remove export of spy and any dart:mirrors based API from mockito.dart. Users may import as package:mockito/mirrors.dart going forward.
  • Deprecated mockito_no_mirrors.dart; replace with mockito.dart.
  • Require Dart SDK >=1.21.0 <2.0.0 to use generic methods.


  • Add a new thenThrow method to the API.
  • Document thenAnswer in the README.
  • Add more dartdoc.


  • Add a new typed API that is compatible with Dart Dev Compiler; documented in


  • Move the reflection-based spy code into a private source file. Now package:mockito/mockito.dart includes this reflection-based API, and a new package:mockito/mockito_no_mirrors.dart doesn't require mirrors.


  • Equality matcher used by default to simplify matching collections as arguments. Should be non-breaking change in most cases, otherwise consider using argThat(identical(arg)).


  • Added support for spy.


  • Migrate from the unittest package to use the new test package.
  • Format code using dartformat

1. Depend on it

Add this to your package's pubspec.yaml file:

  mockito: "^2.2.3"

2. Install it

You can install packages from the command line:

with pub:

$ pub get

with Flutter:

$ flutter packages get

Alternatively, your editor might support pub get or packages get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:

import 'package:mockito/mockito.dart';
Version Uploaded Documentation Archive
2.2.3 Feb 12, 2018 Go to the documentation of mockito 2.2.3 Download mockito 2.2.3 archive
2.2.2 Feb 9, 2018 Go to the documentation of mockito 2.2.2 Download mockito 2.2.2 archive
2.2.1 Nov 16, 2017 Go to the documentation of mockito 2.2.1 Download mockito 2.2.1 archive
2.2.0 Aug 15, 2017 Go to the documentation of mockito 2.2.0 Download mockito 2.2.0 archive
2.1.0 Jul 31, 2017 Go to the documentation of mockito 2.1.0 Download mockito 2.1.0 archive
2.0.2 Mar 10, 2017 Go to the documentation of mockito 2.0.2 Download mockito 2.0.2 archive
1.0.1 Sep 28, 2016 Go to the documentation of mockito 1.0.1 Download mockito 1.0.1 archive
1.0.0 Aug 5, 2016 Go to the documentation of mockito 1.0.0 Download mockito 1.0.0 archive
0.11.0 Sep 14, 2015 Go to the documentation of mockito 0.11.0 Download mockito 0.11.0 archive
0.10.1 May 13, 2015 Go to the documentation of mockito 0.10.1 Download mockito 0.10.1 archive

All 17 versions...


This feature is new.
We welcome feedback.
More details: scoring.

We analyzed this package, and provided a score, details, and suggestions below.

  • completed on Feb 12, 2018
  • Dart: 2.0.0-dev.20.0
  • pana: 0.10.1


Describes how popular the package is relative to other packages. [more]
94 / 100
Code health derived from static analysis. [more]
100 / 100
Reflects how tidy and up-to-date the package is. [more]
100 / 100
Overall score:
Weighted score of the above. [more]


Detected platforms: Flutter, web, other

No platform restriction found in primary library package:mockito/mockito.dart.


  • The description is too short.

    Add more detail about the package, what it does and what is its target use case. Try to write at least 60 characters.

  • Maintain an example.

    Create a short demo in the example/ directory to show how to use this package. Common file name patterns include: main.dart, example.dart or you could also use mockito.dart.


Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.0.0-dev.16.0 <2.0.0
collection ^1.1.0 1.14.5
matcher ^0.12.0 0.12.1+4
meta ^1.0.4 1.1.2
test >=0.12.0 <0.13.0 0.12.30+3
Transitive dependencies
analyzer 0.31.1
args 1.3.0
async 2.0.3 2.0.4
barback 0.15.2+14
boolean_selector 1.0.2
charcode 1.1.1
cli_util 0.1.2+1
convert 2.0.1
crypto 2.0.2+1
csslib 0.14.1
front_end 0.1.0-alpha.9
glob 1.1.5
html 0.13.2+2
http 0.11.3+16
http_multi_server 2.0.4
http_parser 3.1.1
io 0.3.2+1
isolate 1.1.0
js 0.6.1
kernel 0.3.0-alpha.9
logging 0.11.3+1
mime 0.9.6
multi_server_socket 1.0.1
node_preamble 1.4.0
package_config 1.0.3
package_resolver 1.0.2
path 1.5.1
plugin 0.2.0+2
pool 1.3.4
pub_semver 1.3.2
shelf 0.7.2
shelf_packages_handler 1.0.3
shelf_static 0.2.7
shelf_web_socket 0.2.2
source_map_stack_trace 1.1.4
source_maps 0.10.4
source_span 1.4.0
stack_trace 1.9.1
stream_channel 1.6.3
string_scanner 1.0.2
term_glyph 1.0.0
typed_data 1.1.5
utf 0.9.0+4
watcher 0.9.7+7
web_socket_channel 1.0.6 1.0.7
yaml 2.1.13