The functions

Stable entrypoints are: when(), mock(), unstub(), verify(), spy(). Experimental or new function introduces with v1.0.x are: when2(), expect(), verifyNoUnwantedInteractions(), verifyStubbedInvocationsAreUsed(), patch()

mockito.when(obj, strict=True)

Central interface to stub functions on a given obj

obj should be a module, a class or an instance of a class; it can be a Dummy you created with mock(). when exposes a fluent interface where you configure a stub in three steps:

when(<obj>).<method_name>(<args>).thenReturn(<value>)

Compared to simple patching, stubbing in mockito requires you to specify concrete args for which the stub will answer with a concrete <value>. All invocations that do not match this specific call signature will be rejected. They usually throw at call time.

Stubbing in mockito’s sense thus means not only to get rid of unwanted side effects, but effectively to turn function calls into constants.

E.g.:

# Given ``dog`` is an instance of a ``Dog``
when(dog).bark('Grrr').thenReturn('Wuff')
when(dog).bark('Miau').thenRaise(TypeError())

# With this configuration set up:
assert dog.bark('Grrr') == 'Wuff'
dog.bark('Miau')  # will throw TypeError
dog.bark('Wuff')  # will throw unwanted interaction

Stubbing can effectively be used as monkeypatching; usage shown with the with context managing:

with when(os.path).exists('/foo').thenReturn(True):
    ...

Most of the time verifying your interactions is not necessary, because your code under tests implicitly verifies the return value by evaluating it. See verify() if you need to, see also expect() to setup expected call counts up front.

If your function is pure side effect and does not return something, you can omit the specific answer. The default then is None:

when(manager).do_work()

when verifies the method name, the expected argument signature, and the actual, factual arguments your code under test uses against the original object and its function so its easier to spot changing interfaces.

Sometimes it’s tedious to spell out all arguments:

from mockito import ANY, ARGS, KWARGS
when(requests).get('http://example.com/', **KWARGS).thenReturn(...)
when(os.path).exists(ANY)
when(os.path).exists(ANY(str))

Note

You must unstub() after stubbing, or use with statement.

Set strict=False to bypass the function signature checks.

See related when2() which has a more pythonic interface.

mockito.when2(fn, *args, **kwargs)

Stub a function call with the given arguments

Exposes a more pythonic interface than when(). See when() for more documentation.

Returns AnswerSelector interface which exposes thenReturn, thenRaise, thenAnswer, and thenCallOriginalImplementation as usual. Always strict.

Usage:

# Given `dog` is an instance of a `Dog`
when2(dog.bark, 'Miau').thenReturn('Wuff')

Note

You must unstub() after stubbing, or use with statement.

mockito.patch(fn, attr_or_replacement, replacement=None)

Patch/Replace a function.

This is really like monkeypatching, but note that all interactions will be recorded and can be verified. That is, using patch you stay in the domain of mockito.

Two ways to call this. Either:

patch(os.path.exists, lambda str: True)  # two arguments
# OR
patch(os.path, 'exists', lambda str: True)  # three arguments

If called with three arguments, the mode is not strict to allow adding methods. If called with two arguments, mode is always strict.

Note

You must unstub() after stubbing, or use with statement.

mockito.expect(obj, strict=True, times=None, atleast=None, atmost=None, between=None)

Stub a function call, and set up an expected call count.

Usage:

# Given `dog` is an instance of a `Dog`
expect(dog, times=1).bark('Wuff').thenReturn('Miau')
dog.bark('Wuff')
dog.bark('Wuff')  # will throw at call time: too many invocations

# maybe if you need to ensure that `dog.bark()` was called at all
verifyNoUnwantedInteractions()

Note

You must unstub() after stubbing, or use with statement.

See when(), when2(), verifyNoUnwantedInteractions()

mockito.mock(config_or_spec=None, spec=None, strict=OMITTED)

Create ‘empty’ objects (‘Mocks’).

Will create an empty unconfigured object, that you can pass around. All interactions (method calls) will be recorded and can be verified using verify() et.al.

A plain mock() will be not strict, and thus all methods regardless of the arguments will return None.

Note

Technically all attributes will return an internal interface. Because of that a simple if mock().foo: will surprisingly pass.

If you set strict to True: mock(strict=True) all unexpected interactions will raise an error instead.

You configure a mock using when(), when2() or expect(). You can also very conveniently just pass in a dict here:

response = mock({'text': 'ok', 'raise_for_status': lambda: None})

You can also create an empty Mock which is specced against a given spec: mock(requests.Response). These mock are by default strict, thus they raise if you want to stub a method, the spec does not implement. Mockito will also match the function signature.

You can pre-configure a specced mock as well:

response = mock({'json': lambda: {'status': 'Ok'}},
                spec=requests.Response)

Mocks are by default callable. Configure the callable behavior using when:

dummy = mock()
when(dummy).__call__(1).thenReturn(2)

All other magic methods must be configured this way or they will raise an AttributeError.

See verify() to verify your interactions after usage.

mockito.unstub(*objs)

Unstubs all stubbed methods and functions

If you don’t pass in any argument, all registered mocks and patched modules, classes etc. will be unstubbed.

Note that additionally, the underlying registry will be cleaned. After an unstub you can’t verify() anymore because all interactions will be forgotten.

mockito.forget_invocations(*objs)

Forget all invocations of given objs.

If you already call mocks during your setup routine, you can now call forget_invocations at the end of your setup, and have a clean ‘recording’ for your actual test code. T.i. you don’t have to count the invocations from your setup code anymore when using verify() afterwards.

mockito.spy(object)

Spy an object.

Spying means that all functions will behave as before, so they will be side effects, but the interactions can be verified afterwards.

Returns Dummy-like, almost empty object as proxy to object.

The returned object must be injected and used by the code under test; after that all interactions can be verified as usual. T.i. the original object will not be patched, and has no further knowledge as before.

E.g.:

import time
time = spy(time)
# inject time
do_work(..., time)
verify(time).time()
mockito.spy2(fn) None

Spy usage of given fn.

Patches the module, class or object fn lives in, so that all interactions can be recorded; otherwise executes fn as before, so that all side effects happen as before.

E.g.:

import time
spy2(time.time)
do_work(...)  # nothing injected, uses global patched `time` module
verify(time).time()

Note that builtins often cannot be patched because they’re read-only.

This looks like a plethora of verification functions, and especially since you often don’t need to verify at all.

mockito.verify(obj, times=1, atleast=None, atmost=None, between=None, inorder=False)

Central interface to verify interactions.

verify uses a fluent interface:

verify(<obj>, times=2).<method_name>(<args>)

args can be as concrete as necessary. Often a catch-all is enough, especially if you’re working with strict mocks, bc they throw at call time on unwanted, unconfigured arguments:

from mockito import ANY, ARGS, KWARGS
when(manager).add_tasks(1, 2, 3)
...
# no need to duplicate the specification; every other argument pattern
# would have raised anyway.
verify(manager).add_tasks(1, 2, 3)  # duplicates `when`call
verify(manager).add_tasks(*ARGS)
verify(manager).add_tasks(...)       # Py3
verify(manager).add_tasks(Ellipsis)  # Py2
mockito.verifyNoMoreInteractions(*objs)
mockito.verifyZeroInteractions(*objs)

Verify that no methods have been called on given objs.

Note that strict mocks usually throw early on unexpected, unstubbed invocations. Partial mocks (‘monkeypatched’ objects or modules) do not support this functionality at all, bc only for the stubbed invocations the actual usage gets recorded. So this function is of limited use, nowadays.

mockito.verifyNoUnwantedInteractions(*objs)

Verifies that expectations set via expect are met

E.g.:

expect(os.path, times=1).exists(...).thenReturn(True)
os.path('/foo')
verifyNoUnwantedInteractions(os.path)  # ok, called once

If you leave out the argument all registered objects will be checked.

Note

DANGERZONE: If you did not unstub() correctly, it is possible that old registered mocks, from other tests leak.

See related expect()

mockito.verifyStubbedInvocationsAreUsed(*objs)

Ensure stubs are actually used.

This functions just ensures that stubbed methods are actually used. Its purpose is to detect interface changes after refactorings. It is meant to be invoked usually without arguments just before unstub().