Ignore implementation_imports

Generated code may import 'src' files.

PiperOrigin-RevId: 382756565
1 file changed
tree: dcf957bf19d22a141eac53fe86fe5cc8954618d8
  1. .github/
  2. bin/
  3. example/
  4. lib/
  5. test/
  6. tool/
  7. .gitignore
  8. analysis_options.yaml
  9. build.yaml
  10. CHANGELOG.md
  12. FAQ.md
  15. pubspec.yaml
  16. README.md
  17. upgrading-to-mockito-3.md


Mock library for Dart inspired by Mockito.

Pub Build Status

Let's create mocks

Mockito 5.0.0 supports Dart's new null safety language feature in Dart 2.12, primarily with code generation.

To use Mockito‘s generated mock classes, add a build_runner dependency in your package’s pubspec.yaml file, under dev_dependencies; something like build_runner: ^1.11.0.

For alternatives to the code generation API, see the NULL_SAFETY_README.

Let's start with a Dart library, cat.dart:

import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'cat.mocks.dart';

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

// Annotation which generates the cat.mocks.dart library and the MockCat class.
void main() {
  // Create mock object.
  var cat = MockCat();

By annotating a library element (such as a test file‘s main function, or a class) with @GenerateMocks, you are directing Mockito’s code generation to write a mock class for each “real” class listed, in a new library.

The next step is to run build_runner in order to generate this new library:

dart run build_runner build

build_runner will generate a file with a name based on the file containing the @GenerateMocks annotation. In the above cat.dart example, we import the generated library as cat.mocks.dart.

The generated mock class, MockCat, extends Mockito's Mock class and implements the Cat class, giving us a class which supports stubbing and verifying.

Let's verify some behavior!

// Interact with the mock object.
// Verify the interaction.

Once created, the mock instance will remember all interactions. Then you can selectively verify (or verifyInOrder, or verifyNever) the interactions you are interested in.

How about some stubbing?

// Stub a mock method before interacting.
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");

The when, thenReturn, thenAnswer, and thenThrow APIs provide a stubbing mechanism to override this behavior. Once stubbed, the method will always return stubbed value regardless of how many times it is called. If a method invocation matches multiple stubs, the one which was declared last will be used.

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((_) async => '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 arguments with matchers
when(cat.eatFood(argThat(startsWith("dry")), hungry: 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, captureThat, 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("backyard", null)); // OK: no arg matchers.
verify(cat.hunt(argThat(contains("yard")), null)); // BAD: adjacent null.
verify(cat.hunt(argThat(contains("yard")), argThat(isNull))); // OK: wrapped in an arg matcher.
verify(cat.eatFood("Milk", hungry: null)); // BAD: null as a named argument.
verify(cat.eatFood("Milk", hungry: argThat(isNull))); // BAD: null as a named argument.

Named arguments

Mockito currently has an awkward nuisance to its 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(true);
when(cat.eatFood(any, hungry: argThat(isNotNull, named: 'hungry'))).thenReturn(false);
when(cat.eatFood(any, hungry: captureAnyNamed('hungry'))).thenReturn(false);
when(cat.eatFood(any, hungry: captureThat(isNotNull, named: 'hungry'))).thenReturn(true);

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

Verifying exact number of invocations / at least x / never

Use verify or verifyNever:


// Exact number of invocations

// Or using matcher

// Or never called

Verification in order

Use verifyInOrder:


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

Use verifyZeroInteractions:


Finding redundant invocations

Use verifyNoMoreInteractions:


Capturing arguments for further assertions

Use the captureAny, captureThat, and captureAnyNamed argument matchers:

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

Use untilCalled:

// 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)); // Completes immediately.

Writing a fake

You can also write a simple fake class that implements a real class, by extending Fake. Fake allows your subclass to satisfy the implementation of your real class, without overriding the methods that aren't used in your test; the Fake class implements the default behavior of throwing UnimplementedError (which you can override in your fake class):

// Fake class
class FakeCat extends Fake implements Cat {
  bool eatFood(String food, {bool? hungry}) {
    print('Fake eat $food');
    return true;

void main() {
  // Create a new fake Cat at runtime.
  var cat = FakeCat();

  cat.eatFood("Milk"); // Prints 'Fake eat Milk'.
  cat.sleep(); // Throws.

Resetting mocks

Use reset:

// Clearing collected interactions:

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


Use logInvocations and throwOnMissingStub:

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

Best Practices

Testing with real objects is preferred over testing with mocks - if you can construct a real instance for your tests, you should! If there are no calls to verify in your test, it is a strong signal that you may not need mocks at all, though it‘s also OK to use a Mock like a stub. When it’s not possible to use the real object, a tested implementation of a fake is the next best thing - it's more likely to behave similarly to the real class than responses stubbed out in tests. Finally an object which extends Fake using manually overridden methods is preferred over an object which extends Mock used as either a stub or a mock.

A class which extends Mock should never stub out its own responses with when in its constructor or anywhere else. Stubbed responses should be defined in the tests where they are used. For responses controlled outside of the test use @override methods for either the entire interface, or with extends Fake to skip some parts of the interface.

Similarly, a class which extends Mock should never have any @override methods. These can‘t be stubbed by tests and can’t be tracked and verified by Mockito. A mix of test defined stubbed responses and mock defined overrides will lead to confusion. It is OK to define static utilities on a class which extends Mock if it helps with code structure.

Frequently asked questions

Read more information about this package in the FAQ.