• Stars
    star
    618
  • Rank 69,834 (Top 2 %)
  • Language
    Dart
  • License
    Apache License 2.0
  • Created almost 10 years ago
  • Updated 25 days ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Mockito-inspired mock library for Dart

Dart CI Pub package publisher

Mock library for Dart inspired by Mockito.

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

// Annotation which generates the cat.mocks.dart library and the MockCat class.
@GenerateNiceMocks([MockSpec<Cat>()])
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;
}

void main() {
  // Create mock object.
  var cat = MockCat();
}

By annotating the import of a .mocks.dart library with @GenerateNiceMocks, 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:

flutter pub run build_runner build
# OR
dart run build_runner build

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

NOTE: by default only annotations in files under test/ are processed, if you want to add Mockito annotations in other places, you will need to add a build.yaml file to your project, see this SO answer.

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.
cat.sound();
// Verify the interaction.
verify(cat.sound());

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.
when(cat.sound()).thenReturn("Purr");
expect(cat.sound(), "Purr");

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

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

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

// You can stub a method to throw.
when(cat.lives).thenThrow(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");

// We can stub a method with multiple calls that happened in a particular order.
when(cat.sound()).thenReturnInOrder(["Purr", "Meow"]);
expect(cat.sound(), "Purr");
expect(cat.sound(), "Meow");
expect(() => cat.sound(), throwsA(isA<StateError>()));

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. It is worth noting that stubbing and verifying only works on methods of a mocked class; in this case, an instance of MockCat must be used, not an instance of Cat.

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
when(mock.methodThatReturnsAFuture())
    .thenReturn(Future.value('Stub'));
when(mock.methodThatReturnsAStream())
    .thenReturn(Stream.fromIterable(['Stub']));

// GOOD
when(mock.methodThatReturnsAFuture())
    .thenAnswer((_) async => 'Stub');
when(mock.methodThatReturnsAStream())
    .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 `any`
when(cat.eatFood(any)).thenReturn(false);

// ... or plain arguments themselves
when(cat.eatFood("fish")).thenReturn(true);

// ... including collections
when(cat.walk(["roof","tree"])).thenReturn(2);

// ... or matchers
when(cat.eatFood(argThat(startsWith("dry")))).thenReturn(false);

// ... 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.
verify(cat.eatFood("fish"));
verify(cat.walk(["roof","tree"]));
verify(cat.eatFood(argThat(contains("food"))));

// You can verify setters.
cat.lives = 9;
verify(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 using 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:

cat.sound();
cat.sound();

// Exact number of invocations
verify(cat.sound()).called(2);

// Or using matcher
verify(cat.sound()).called(greaterThan(1));

// Or never called
verifyNever(cat.eatFood(any));

Verification in order

Use verifyInOrder:

cat.eatFood("Milk");
cat.sound();
cat.eatFood("Fish");
verifyInOrder([
  cat.eatFood("Milk"),
  cat.sound(),
  cat.eatFood("Fish")
]);

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:

verifyZeroInteractions(cat);

Finding redundant invocations

Use verifyNoMoreInteractions:

cat.sound();
verify(cat.sound());
verifyNoMoreInteractions(cat);

Capturing arguments for further assertions

Use the captureAny, captureThat, and captureAnyNamed argument matchers:

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

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

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

Waiting for an interaction

Use untilCalled:

// Waiting for a call.
cat.eatFood("Fish");
await untilCalled(cat.chew()); // Completes when cat.chew() is called.

// Waiting for a call that has already happened.
cat.eatFood("Fish");
await untilCalled(cat.eatFood(any)); // Completes immediately.

Nice mocks vs classic mocks

Mockito provides two APIs for generating mocks, the @GenerateNiceMocks annotation and the @GenerateMocks annotation. The recommended API is @GenerateNiceMocks. The difference between these two APIs is in the behavior of a generated mock class when a method is called and no stub could be found. For example:

void main() {
  var cat = MockCat();
  cat.sound();
}

The Cat.sound method returns a non-nullable String, but no stub has been made with when(cat.sound()), so what should the code do? What is the "missing stub" behavior?

  • The "missing stub" behavior of a mock class generated with @GenerateMocks is to throw an exception.
  • The "missing stub" behavior of a mock class generated with @GenerateNiceMocks is to return a "simple" legal value (for example, a non-null value for a non-nullable return type). The value should not be used in any way; it is returned solely to avoid a runtime type exception.

Mocking a Function type

To create mocks for Function objects, write an abstract class with a method for each function type signature that needs to be mocked. The methods can be torn off and individually stubbed and verified.

@GenerateMocks([Cat, Callbacks])
import 'cat_test.mocks.dart'

abstract class Callbacks {
  Cat findCat(String name);
}

void main() {
  var mockCat = MockCat();
  var findCatCallback = MockCallbacks().findCat;
  when(findCatCallback('Pete')).thenReturn(mockCat);
}

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 {
  @override
  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:
cat.eatFood("Fish");
clearInteractions(cat);
cat.eatFood("Fish");
verify(cat.eatFood("Fish")).called(1);

// Resetting stubs and collected interactions:
when(cat.eatFood("Fish")).thenReturn(true);
cat.eatFood("Fish");
reset(cat);
when(cat.eatFood(any)).thenReturn(false);
expect(cat.eatFood("Fish"), false);

Debugging

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:
throwOnMissingStub(cat);

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. Data models never need to be mocked if they can be constructed with stubbed data. 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 implementation. It should not define any @override methods, and it should not mixin any implementations. Actual member definitions 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.

More Repositories

1

sdk

The Dart SDK, including the VM, dart2js, core libraries, and more.
Dart
9,763
star
2

language

Design of the Dart language
TeX
2,536
star
3

dart-pad

An online Dart editor with support for console, web, and Flutter apps
Dart
1,637
star
4

pub

The pub command line tool
Dart
1,024
star
5

http

A composable API for making HTTP requests in Dart.
Dart
994
star
6

site-www

Source for Dart website
Dart
922
star
7

shelf

Web server middleware for Dart
Dart
870
star
8

build

A build system for Dart written in Dart
Dart
763
star
9

pub-dev

The pub.dev website
Dart
762
star
10

dart-vim-plugin

Syntax highlighting for Dart in Vim
Vim Script
635
star
11

dart_style

An opinionated formatter/linter for Dart code
Dart
629
star
12

linter

Linter for Dart.
Dart
626
star
13

samples

A collection of Dart code samples by Dart DevRel
Dart
576
star
14

test

A library for writing unit tests in Dart.
Dart
486
star
15

source_gen

Automatic source code generation for Dart
Dart
479
star
16

dartdoc

API documentation tool for Dart.
Dart
459
star
17

markdown

A Dart markdown library
Dart
428
star
18

code_builder

A fluent API for generating valid Dart source code
Dart
416
star
19

web_socket_channel

StreamChannel wrappers for WebSockets.
Dart
405
star
20

leak_tracker

A framework for memory leak tracking for Dart and Flutter applications.
Dart
369
star
21

ffigen

FFI binding generator
Dart
364
star
22

collection

The collection package for Dart contains a number of separate libraries with utility functions and classes that makes working with collections easier.
Dart
359
star
23

logging

A Dart package for debug and error logging.
Dart
311
star
24

wasm

Utilities for loading and running WASM modules from Dart code
Dart
309
star
25

async

A Dart package that contains tools to work with asynchronous computations.
Dart
300
star
26

html

Dart port of html5lib. For parsing HTML/HTML5 with Dart. Works in the client and on the server.
Dart
268
star
27

crypto

A set of cryptographic functions implemented in pure Dart.
Dart
261
star
28

path

A string-based path manipulation library.
Dart
215
star
29

webdev

A CLI for Dart web development.
Dart
210
star
30

oauth2

An OAuth2 client library for Dart.
Dart
208
star
31

args

A command-line argument parsing library for Dart.
Dart
202
star
32

pana

Package ANAlysis for Dart
Dart
190
star
33

setup-dart

A GitHub Action to install and setup a Dart SDK.
Dart
176
star
34

yaml

A Dart YAML parser.
Dart
163
star
35

jnigen

Experimental bindings generator for Java bindings through dart:ffi and JNI.
Dart
154
star
36

http2

A HTTP/2 implementation for dart.
Dart
150
star
37

ffi

Utilities for working with Foreign Function Interface (FFI) code
Dart
149
star
38

homebrew-dart

Dart team's official tap for homebrew.
Ruby
147
star
39

sample-pop_pop_win

"Pop, Pop, Win!" is an implementation of Minesweeper in Dart.
Dart
146
star
40

usage

A Google Analytics wrapper for command-line, web, and Flutter apps.
Dart
143
star
41

watcher

A file system watcher library for Dart.
Dart
135
star
42

stack_trace

A package for manipulating stack traces and printing them readably.
Dart
128
star
43

gcloud

High-level interfaces to Google Cloud Platform APIs
Dart
127
star
44

mime

Dart package for working with MIME type definitions and for processing streams of MIME multipart media types.
Dart
124
star
45

stream_transform

Dart utility methods to create StreamTransfomer instances to manipulate Streams
Dart
118
star
46

lints

Official Dart lint rules; the core and recommended set of lints suggested by the Dart team.
Dart
106
star
47

coverage

Dart coverage data manipulation and formatting
Dart
102
star
48

appengine

Dart support for App Engine managed VMs
Dart
93
star
49

csslib

A library for parsing CSS.
Dart
92
star
50

benchmark_harness

The official benchmark harness for Dart
Dart
92
star
51

web

Lightweight browser API bindings built around JS static interop.
Dart
89
star
52

sse

Dart Server Sent Events package
Dart
89
star
53

fake_async

Fake asynchronous events for deterministic testing.
Dart
87
star
54

native

Dart packages related to FFI and native assets bundling.
Dart
74
star
55

matcher

A declarative API for specifying expectations.
Dart
70
star
56

json_rpc_2

A Dart implementation of the JSON-RPC 2.0 spec.
Dart
70
star
57

convert

Conversion utilities
Dart
68
star
58

characters

A package for characters represented as unicode extended grapheme clusters
Dart
67
star
59

dart-docker

Docker images for the Dart programming language (https://dart.dev)
Dart
65
star
60

pub_semver

A package for working with Pub/semver-style versions and version constraints
Dart
62
star
61

string_scanner

A class for parsing strings using a sequence of patterns.
Dart
59
star
62

cli_util

A library to help in building Dart command-line apps
Dart
59
star
63

glob

Bash-style filename globbing for Dart.
Dart
55
star
64

pubspec_parse

Simple package for parsing pubspec.yaml files with a type-safe API and rich error reporting
Dart
50
star
65

i18n

A general mono-repo for Dart i18n and l10n packages.
Dart
50
star
66

pool

A class for managing a finite pool of resources.
Dart
48
star
67

stream_channel

An abstraction for two-way communication channels.
Dart
47
star
68

io

Utilities for the Dart VM's dart:io.
Dart
47
star
69

fixnum

Fixed-width integer library for Dart.
Dart
44
star
70

clock

A fakeable wrapper for dart:core clock APIs.
Dart
40
star
71

site-shared

Content shared across Dart websites
Dart
40
star
72

co19

A Dart language and library conformance test suite
Dart
36
star
73

http_parser

A platform-independent Dart package for parsing and serializing HTTP formats.
Dart
35
star
74

ecosystem

This repository is home to general Dart Ecosystem tools and packages.
Dart
35
star
75

typed_data

Utility functions and classes that makes working with typed data lists easier in Dart
Dart
35
star
76

source_span

A library for identifying source spans and locations.
Dart
28
star
77

http_multi_server

A dart:io HttpServer wrapper that handles requests from multiple servers.
Dart
27
star
78

native_synchronization

Low-level synchronization primitives built using dart:ffi.
Dart
26
star
79

dartbug.com

The redirect service for Dart issues and bugs.
Dart
23
star
80

bazel_worker

Dart integration for Bazel build system
Dart
23
star
81

boolean_selector

A flexible syntax for boolean expressions.
Dart
23
star
82

os_detect

Dart multi-platform operating system identification
Dart
22
star
83

dart-syntax-highlight

Tools and documentation for how Dart code is formatted
Dart
21
star
84

yaml_edit

A library for YAML manipulation with comment and whitespace preservation.
Dart
21
star
85

tools

This repository is home to tooling related Dart packages.
Dart
21
star
86

api.dart.dev

Dart API docs
Python
19
star
87

dart_ci

Tools used by Dart's continuous integration (CI) testing that aren't needed by Dart SDK contributors. Mirrored from dart.googlesource.com/dart_ci. Do not land pull requests on Github.
Dart
18
star
88

test_process

A Dart package for testing subprocesses
Dart
17
star
89

term_glyph

Useful glyphs and Windows-safe equivalents
Dart
16
star
90

browser_launcher

Provides a standardized way to launch web browsers.
Dart
16
star
91

source_maps

A package to programmatically manipulate source maps.
Dart
15
star
92

grpc_cronet

Flutter dart:grpc implementation that uses the Cronet native library.
Dart
14
star
93

timing

A Dart package for tracking time spent in child operations
Dart
14
star
94

package_config

Support for working with Package Resolution Configuration files
Dart
14
star
95

root_certificates

The set of root certificates trusted by dart:io's default SecurityContext. Taken from Mozilla's NSS library.
C++
11
star
96

test_descriptor

Provides a convenient, easy-to-read API for defining and verifying directory structures in tests
Dart
10
star
97

dartlang_project_templates

Project templates for new repos under the dart-lang organization
Dart
8
star
98

source_map_stack_trace

Convert stack traces generated by dart2js-compiled code into readable native Dart stack traces
Dart
7
star
99

.github

GitHub default community health file for dart-lang repos
7
star
100

test_reflective_loader

Discover tests and test suites using reflection
Dart
5
star