mockito 3.0.1

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 = 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:
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.

A quick word on async stubbing #

Using thenReturn to return a Future or Stream will throw an ArgumentError. This is because it can lead to unexpected behaviors. For example:

  • If the method is stubbed in a different zone than the zone that consumes the Future, unexpected behavior could occur.
  • If the method is stubbed to return a failed Future or Stream and it doesn't get consumed in the same run loop, it might get consumed by the global exception handler instead of an exception handler the consumer applies.

Instead, use thenAnswer to stub methods that return a Future or Stream.

// BAD

    .thenAnswer((_) => Future.value('Stub'));
    .thenAnswer((_) => Stream.fromIterable(['Stub']));

If, for some reason, you desire the behavior of thenReturn, you can return a pre-defined instance.

// Use the above method unless you're sure you want to create the Future ahead
// of time.
final future = Future.value('Stub');
when(mock.methodThatReturnsAFuture()).thenAnswer((_) => future);

Argument matchers #

Mockito provides the concept of the "argument matcher" (using the class ArgMatcher) to capture arguments and to track how named arguments are passed. In most cases, both plain arguments and argument matchers can be passed into mock methods:

// You can use plain arguments themselves:

// ... including 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)).

However, note that null cannot be used as an argument adjacent to ArgMatcher arguments, nor as an un-wrapped value passed as a named argument. For example:

verify(cat.hunt("back yard", null)); // OK: no ArgMatchers.
verify(cat.hunt(argThat(contains("yard")), null)); // BAD: adjacent null.
verify(cat.hunt(argThat(contains("yard")), argThat(isNull))); // OK: wrapped in ArgMatcher.
verify(cat.eatFood("Milk", hungry: null)); // BAD: null as named argument.
verify(cat.eatFood("Milk", hungry: argThat(isNull))); // BAD: null as named argument.

Named arguments #

Mockito currently has an awkward nuisance to it's syntax: named arguments and argument matchers require more specification than you might think: you must declare the name of the argument in the argument matcher. This is because we can't rely on the position of a named argument, and the language doesn't provide a mechanism to answer "Is this element being used as a named element?"

// GOOD: argument matchers include their names.
when(cat.eatFood(any, hungry: anyNamed('hungry'))).thenReturn(0);
when(cat.eatFood(any, hungry: argThat(isNotNull, named: 'hungry'))).thenReturn(0);
when(cat.eatFood(any, hungry: captureAnyNamed('hungry'))).thenReturn(0);
when(cat.eatFood(any, hungry: captureArgThat(isNotNull, named: 'hungry'))).thenReturn(0);

// BAD: argument matchers do not include their names.
when(cat.eatFood(any, hungry: any)).thenReturn(0);
when(cat.eatFood(any, hungry: argThat(isNotNull))).thenReturn(0);
when(cat.eatFood(any, hungry: captureAny)).thenReturn(0);
when(cat.eatFood(any, hungry: captureArgThat(isNotNull))).thenReturn(0);

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);

Debugging #

// 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:

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.

Argument matchers work by storing the wrapped arguments, one after another, until the when (or verify) call gathers everything that has been stored, and creates an InvocationMatcher with the arguments. This is a simple process for positional arguments: the order in which the arguments has been stored should be preserved for matching an invocation. Named arguments are trickier: their evaluation order is not specified, so if Mockito blindly stored them in the order of their evaluation, it wouldn't be able to match up each argument matcher with the correct name. This is why each named argument matcher must repeat it's own name. foo: anyNamed('foo') tells Mockito to store an argument matcher for an invocation under the name 'foo'.

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 = MockUtils();
var mockStringUtils = 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

3.0.1 #

  • Replace the dependency on the test package with a dependency on the new test_api package. This dramatically reduces mockito's transitive dependencies.
  • Internal improvements to tests and examples.

3.0.0 #

  • Deprecate the typed API; instead of wrapping other Mockito API calls, like any, argThat, captureAny, and captureArgThat, with a call to typed, the regular API calls are to be used by themselves. Passing any and captureAny as named arguments must be replaced with anyNamed() and captureAnyNamed, respectively. Passing argThat and captureThat as named arguments must include the named parameter.

  • Introduce a backward-and-forward compatible API to help users migrate to Mockito 3. See more details in the upgrading-to-mockito-3 doc.

  • thenReturn now throws an ArgumentError if either a Future or Stream is provided. thenReturn calls with futures and streams should be changed to thenAnswer. See the README for more information.

  • Support stubbing of void methods in Dart 2.

  • thenReturn and thenAnswer now support generics and infer the correct types from the when call.

  • Completely remove the mirrors implementation of Mockito (mirrors.dart).

  • Fix compatibility with new noSuchMethod Forwarding feature of Dart 2. This is thankfully a mostly backwards-compatible change. This means that this version of Mockito should continue to work:

    • with Dart >=2.0.0-dev.16.0,
    • with Dart 2 runtime semantics (i.e. with dart --preview-dart-2, or with Flutter Beta 3), and
    • with the new noSuchMethod Forwarding feature, when it lands in CFE, and when it lands in DDC.

    This change, when combined with noSuchMethod Forwarding, will break a few code paths which do not seem to be frequently used. Two examples:

    class A {
      int fn(int a, [int b]) => 7;
    class MockA extends Mock implements A {}
    var a = new MockA();
    when(a.fn(typed(any), typed(any))).thenReturn(0);

    This used to print null, because only one argument was passed, which did not match the two-argument stub. Now it will print 0, as the real call contains a value for both the required argument, and the optional argument.

    a.fn(2, 3);
    print(verify(a.fn(typed(captureAny), typed(captureAny))).captured);

    This used to print [2, 3], because only the second call matched the verify call. Now, it will print [1, null, 2, 3], as both real calls contain a value for both the required argument, and the optional argument.

  • Upgrade package dependencies.

  • Throw an exception when attempting to stub a method on a Mock object that already exists.

2.2.0 #

  • Add new feature to wait for an interaction: untilCalled. See the README for documentation.
  • capture* calls outside of a verify* call no longer capture arguments.
  • Some collections require stricter argument matching. For example, a stub like: mock.methodWithListArgs([1,2,3].map((e) => e*2)) (note the Iterable argument) will no longer match the following stub: when(mock.methodWithListArgs([42])).thenReturn(7);.

2.1.0 #

  • 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.

2.0.2 #

  • 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.

2.0.1 #

  • Add a new throwOnMissingStub method to the API.

2.0.0 #

  • Removed mockito_no_mirrors.dart

2.0.0-dev #

  • 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.

1.0.1 #

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

1.0.0 #

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

0.11.1 #

  • 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.

0.11.0 #

  • 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)).

0.10.0 #

  • Added support for spy.

0.9.0 #

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

Use this package as a library

1. Depend on it

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

  mockito: ^3.0.1

2. Install it

You can install packages from the command line:

with pub:

$ pub get

with Flutter:

$ flutter pub get

Alternatively, your editor might support pub get or flutter pub 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';
Describes how popular the package is relative to other packages. [more]
Code health derived from static analysis. [more]
Reflects how tidy and up-to-date the package is. [more]
Weighted score of the above. [more]
Learn more about scoring.

We analyzed this package on Aug 29, 2019, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.4.0
  • pana: 0.12.20


Detected platforms: Flutter, other

Primary library: package:mockito/mockito.dart with components: isolate.

Health suggestions

Fix lib/mockito.dart. (-1.49 points)

Analysis of lib/mockito.dart reported 3 hints:

line 42 col 9: 'typed' is deprecated and shouldn't be used.

line 43 col 9: 'typedArgThat' is deprecated and shouldn't be used.

line 44 col 9: 'typedCaptureThat' is deprecated and shouldn't be used.

Maintenance issues and suggestions

Support latest dependencies. (-10 points)

The version constraint in pubspec.yaml does not support the latest published versions for 1 dependency (test_api).

The package description is too short. (-20 points)

Add more detail to the description field of pubspec.yaml. Use 60 to 180 characters to describe the package, what it does, and its target use case.

Maintain an example. (-10 points)

Create a short demo in the example/ directory to show how to use this package.

Common filename patterns include main.dart, example.dart, and mockito.dart. Packages with multiple examples should provide example/

For more information see the pub package layout conventions.


Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.0.0 <3.0.0
collection ^1.1.0 1.14.12
matcher ^0.12.3 0.12.3+1 0.12.5
meta ^1.0.4 1.1.7
test_api ^0.1.1 0.1.1 0.2.7
Transitive dependencies
async 2.3.0
boolean_selector 1.0.5
charcode 1.1.2
path 1.6.4
source_span 1.5.5
stack_trace 1.9.3
stream_channel 1.7.0 2.0.0
string_scanner 1.0.5
term_glyph 1.1.0
Dev dependencies
build_runner ^1.0.0
build_test ^0.10.0
build_web_compilers ^0.4.0
pedantic ^1.3.0
test ^1.4.0