dart-lang/mockito

Name: mockito

Owner: Dart

Description: Mockito-inspired mock library for Dart

Created: 2014-07-14 10:15:33.0

Updated: 2018-01-18 01:19:04.0

Pushed: 2017-12-15 01:32:22.0

Homepage: https://pub.dartlang.org/packages/mockito

Size: 161

Language: Dart

GitHub Committers

UserMost Recent Commit# Commits

Other Committers

UserEmailMost Recent Commit# Commits

README

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:

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

Let's create mocks
rt 'package:mockito/mockito.dart';

eal class
s Cat {
ring sound() => "Meow";
ol eatFood(String food, {bool hungry}) => true;
t walk(List<String> places);
id sleep() {}
id hunt(String place, String prey) {}
t lives = 9;


ock class
s MockCat extends Mock implements Cat {}

ock creation
cat = new MockCat();
Let's verify some behaviour!
ing mock object
sound();
rify interaction
fy(cat.sound());

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

How about some stubbing?
nstubbed methods return null:
ct(cat.sound(), nullValue);

tubbing - before execution:
(cat.sound()).thenReturn("Purr");
ct(cat.sound(), "Purr");

ou can call it again:
ct(cat.sound(), "Purr");

et's change the stub:
(cat.sound()).thenReturn("Meow");
ct(cat.sound(), "Meow");

ou can stub getters:
(cat.lives).thenReturn(9);
ct(cat.lives, 9);

ou can stub a method to throw:
(cat.lives).thenThrow(new RangeError('Boo'));
ct(() => cat.lives, throwsRangeError);

e can calculate a response at call time:
responses = ["Purr", "Meow"];
(cat.sound()).thenAnswer(() => responses.removeAt(0));
ct(cat.sound(), "Purr");
ct(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:

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

AD
(mock.methodThatReturnsAFuture())
.thenReturn(new Future.value('Stub'));
(mock.methodThatReturnsAStream())
.thenReturn(new Stream.fromIterable(['Stub']));

OOD
(mock.methodThatReturnsAFuture())
.thenAnswer((_) => new Future.value('Stub'));
(mock.methodThatReturnsAStream())
.thenAnswer((_) => new Stream.fromIterable(['Stub']));

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

se the above method unless you're sure you want to create the Future ahead
f time.
l future = new Future.value('Stub');
(mock.methodThatReturnsAFuture()).thenAnswer((_) => future);
Argument matchers
ou can use arguments itself:
(cat.eatFood("fish")).thenReturn(true);

.. or collections:
(cat.walk(["roof","tree"])).thenReturn(2);

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

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

ou can also verify using an argument matcher:
fy(cat.eatFood("fish"));
fy(cat.walk(["roof","tree"]));
fy(cat.eatFood(argThat(contains("food"))));

ou can verify setters:
lives = 9;
fy(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
sound();
sound();

xact number of invocations:
fy(cat.sound()).called(2);

r using matcher:
fy(cat.sound()).called(greaterThan(1));

r never called:
fyNever(cat.eatFood(any));
Verification in order
eatFood("Milk");
sound();
eatFood("Fish");
fyInOrder([
t.eatFood("Milk"),
t.sound(),
t.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
rifyZeroInteractions(cat);
Finding redundant invocations
sound();
fy(cat.sound());
fyNoMoreInteractions(cat);
Capturing arguments for further assertions
imple capture:
eatFood("Fish");
ct(verify(cat.eatFood(captureAny)).captured.single, "Fish");

apture multiple calls:
eatFood("Milk");
eatFood("Fish");
ct(verify(cat.eatFood(captureAny)).captured, ["Milk", "Fish"]);

onditional capture:
eatFood("Milk");
eatFood("Fish");
ct(verify(cat.eatFood(captureThat(startsWith("F")).captured, ["Fish"]);
Waiting for an interaction
aiting for a call:
eatFood("Fish");
t untilCalled(cat.chew()); //completes when cat.chew() is called

aiting for a call that has already happened:
eatFood("Fish");
t untilCalled(cat.eatFood(any)); //will complete immediately
Resetting mocks
learing collected interactions:
eatFood("Fish");
rInteractions(cat);
eatFood("Fish");
fy(cat.eatFood("Fish")).called(1);

esetting stubs and collected interactions:
(cat.eatFood("Fish")).thenReturn(true);
eatFood("Fish");
t(cat);
(cat.eatFood(any)).thenReturn(false);
ct(cat.eatFood("Fish"), false);
Spy
py creation:
cat = spy(new MockCat(), new Cat());

tubbing - before execution:
(cat.sound()).thenReturn("Purr");

sing mocked interaction:
ct(cat.sound(), "Purr");

sing a real object:
ct(cat.lives, 9);
Debugging
rint all collected invocations of any mock methods of a list of mock objects:
nvocations([catOne, catTwo]);

hrow every time that a mock method is called without a stub being matched:
wOnMissingStub(cat);
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:

s Cat {
ol eatFood(List<String> foods, [List<String> mixins]) => true;
t walk(List<String> places, {Map<String, String> gaits}) => 0;


s MockCat extends Mock implements Cat {}

cat = new MockCat();

OK, what if we try to stub using any:

(cat.eatFood(any)).thenReturn(true);

Let's analyze this code:

rtanalyzer --strong test/cat_test.dart
yzing [lib/cat_test.dart]...
ning] Unsound implicit cast from dynamic to List<String> (test/cat_test.dart, line 12, col 20)
rning found.

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

(cat.eatFood(typed(any)))

rtanalyzer --strong test/cat_test.dart
yzing [lib/cat_test.dart]...
ssues found

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

(cat.eatFood(typed(any), typed(any))).thenReturn(true);
(cat.eatFood(typed(argThat(contains("fish"))))).thenReturn(true);

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

(cat.walk(typed(any), gaits: typed(any, named: 'gaits')))
.thenReturn(true);

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:

(cat.eatFood(null, typed(any))).thenReturn(true); // Throws!
(cat.eatFood(
argThat(equals(null)),
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:

nstubbed methods return null:
ct(cat.sound(), nullValue);

tubbing - before execution:
(cat.sound()).thenReturn("Purr");

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:

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

etting up mockUtils.stringUtils to return a mock StringUtils implementation
(mockUtils.stringUtils).thenReturn(mockStringUtils);

ome tests

AILS!
fy(mockUtils.stringUtils.uppercase()).called(1);
nstead use this:
fy(mockStringUtils.uppercase()).called(1);

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


This work is supported by the National Institutes of Health's National Center for Advancing Translational Sciences, Grant Number U24TR002306. This work is solely the responsibility of the creators and does not necessarily represent the official views of the National Institutes of Health.