NewYour coding agent can read the release notes before it upgrades.Set up the MCP server →
PyPI · #3893 most downloaded on PyPI
Spying framework
Last release 5 months ago
15 Apr 2026
Ships unpredictably
gaps range from 2 weeks to 1.5 years
Most releases are documented
notes for 31 of 48 stable releases
Nothing withdrawn
no release was ever pulled
17 years old
55 releases · first in 2010
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
One column per quarter.
Deprecate verifyNoMoreInteractions in favor of ensureNoUnverifiedInteractions .
First-class async/await and property/descriptor support. Chaining. InOrder.
Enhanced captor, new patch_attr and patch_dict.
Deprecate verifyNoMoreInteractions in favor of ensureNoUnverifiedInteractions.
Deprecate verifyNoUnwantedInteractions in favor of verifyExpectedInteractions.
Context managers now check usage and any expectations (set via expect) on exit. The usage
check can be disabled with the environment variable MOCKITO_CONTEXT_MANAGERS_CHECK_USAGE="0".
The between matcher now supports open ranges, e.g. between=(0,) to assert that at least
0 interactions occurred.
Calling thenAnswer() without arguments is now allowed and is treated like
thenReturn() without arguments: the stubbed method will return None.
Allow ... in fixed argument positions as an ad-hoc any matcher.
Trailing positional ... keeps its existing "rest" semantics.
Expanded mock({...}) constructor shorthands. Refer https://mockito-python.readthedocs.io/en/latest/mock-shorthands.html
Added a first-class InOrder API via mockito.InOrder. The legacy in-order mode only supported one mock at a time;
the new API supports true cross-mock order verification.
Migration (old limited style -> new style)::
# Before (legacy, single-mock order only)
from mockito import inorder
inorder.verify(cat).meow()
inorder.verify(cat).purr()
# Now (preferred, explicit cross-mock order)
from mockito import InOrder
in_order = InOrder(cat, dog)
in_order.verify(cat).meow()
in_order.verify(dog).bark()
The legacy in-order verification mode (inorder.verify(...))
is deprecated in favor of InOrder(...).
Added first-class async/await stubbing support: async callables now preserve
awaitable behavior for thenReturn, thenRaise, and thenAnswer (including
sync and async answer callables), with parity across when, when2,
patch, and expect.
Note that async introspection metadata (e.g. inspect.iscoroutinefunction)
for stub wrappers is currently implemented only on Python 3.12+.
Added first-class property/descriptor stubbing support, including class-level property
stubbing via when(F).p.thenReturn(...) and thenCallOriginalImplementation() support for
property stubs (including chained answers like
thenReturn(...).thenCallOriginalImplementation()). Stubbing instance properties now fails
fast with clear guidance to use class-level stubbing (when(F).p...).
Added chained stubbing and expectations across call/property hops, e.g.
when(cat).meow().purr().thenReturn(...), when(User).query.filter_by(...).first(), and
expect(cat, times=1).meow().purr(), including cleanup that preserves sibling chain branches.
Extend captor to be used as a rest matcher
E.g., support
args = captor()
when(freud).says(*args).thenReturn("Yes.")
assert freud.says("Are", "you", "dreaming?") == "Yes."
assert args.value == ("Are", "you", "dreaming?")
# or
kwargs = captor()
when(freud).does(**kwargs).thenReturn(False)
Added call_captor
call = call_captor()
when(mock).do(call).thenReturn("ok")
mock.do(1, 2, x=3)
assert call.value == ((1, 2), {"x": 3})
Added patch_attr and patch_dict for non-callable monkeypatch-style use cases
(e.g. sys.stdout, sys.argv, and environment/config dictionaries) with
context-manager support and restoration through unstub.
E.g.
patch_attr("sys.argv", ["foo", "bar"])
with patch_attr("sys.stdout", StringIO()) as stdout: ...
with patch_dict(os.environ, {"user": "bob"}): ...
Added explicit partial-unstub targeting by host + attribute name.
This complements method-reference partial unstub (e.g. unstub(cat.meow))
and supports tuple form and shorthand form, including multiple attributes
in one call.
E.g.
unstub(cat.meow)
unstub((cat, "meow"))
unstub(cat, "meow")
unstub((cat, "meow"), (os.path, "exists"))
Also implemented unstub("os.path")
Deprecate verifyNoMoreInteractions in favor of ensureNoUnverifiedInteractions.
Deprecate verifyNoUnwantedInteractions in favor of verifyExpectedInteractions.
Context managers now check usage and any expectations (set via expect) on exit. The usage check can be disabled with the environment variable MOCKITO_CONTEXT_MANAGERS_CHECK_USAGE="0".
The between matcher now supports open ranges, e.g. between=(0,) to assert that at least 0 interactions occurred.
Calling thenAnswer() without arguments is now allowed and is treated like thenReturn() without arguments: the stubbed method will return None.
Added a first-class InOrder API via mockito.InOrder. The legacy in-order mode only supported one mock at a time; the new API supports true cross-mock order verification.
Migration:
# Before from mockito import inorder inorder.verify(cat).meow() inorder.verify(cat).purr() # Now from mockito import InOrder in_order = InOrder(cat) # <== pass multiple objects for cross-mock verification! in_order.verify(cat).meow() in_order.verify(cat).purr()
The legacy in-order verification mode (inorder.verify(...)) is deprecated in favor of InOrder(...).
Added first-class async/await stubbing support: async callables now preserve awaitable behavior for thenReturn, thenRaise, and thenAnswer.
Note
Async introspection metadata (e.g. inspect.iscoroutinefunction) for stub wrappers is currently implemented only on Python 3.12+.
Expanded mock({...}) constructor shorthands; see mock-shorthands.
Added first-class property/descriptor stubbing support.
E.g.:
class F:
@property
def p(self):
return "orig"
when(F).p.thenReturn("stub")
assert F().p == "stub"
Added chained stubbing and expectations across call/property hops, e.g.:
when(cat).meow().purr().thenReturn(...) when(User).query.filter_by(...).first() expect(cat, times=1).meow().purr()
Allow ... in fixed argument positions as an ad-hoc any matcher. Trailing positional ... keeps its existing "rest" semantics.
E.g.:
when(api).call("users", active=...).thenReturn("ok")
assert api.call("users", active=True) == "ok"
api.call("users") # will raise InvocationError, kwarg "active" is missing
when(api).call("users", ...) # used as a rest matcher as before
Extend captor to be used as a rest matcher
E.g., support:
args = captor()
when(freud).says(*args).thenReturn("Yes.")
assert freud.says("Are", "you", "dreaming?") == "Yes."
assert args.value == ("Are", "you", "dreaming?")
# or
kwargs = captor()
when(freud).does(**kwargs).thenReturn(False)
Added call_captor:
call = call_captor()
when(mock).do(call).thenReturn("ok")
mock.do(1, 2, x=3)
assert call.value == ((1, 2), {"x": 3})
Added patch_attr and patch_dict for non-callable monkeypatch-style use cases (e.g. sys.stdout, sys.argv, and environment/config dictionaries) with context-manager support and restoration through unstub.
E.g.:
patch_attr("sys.argv", ["foo", "bar"])
with patch_attr("sys.stdout", StringIO()) as stdout: ...
with patch_dict(os.environ, {"user": "bob"}): ...
Added explicit partial-unstub targeting by host + attribute name. This complements method-reference partial unstub (e.g. unstub(cat.meow)) and supports tuple form and shorthand form, including multiple attributes in one call.
E.g.:
unstub(cat.meow) unstub((cat, "meow")) unstub(cat, "meow") unstub((cat, "meow"), (os.path, "exists"))
Also implemented unstub("os.path") - the string variant.
Packaging is now fully defined via pyproject.toml (hatchling backend); the obsolete setup.py shim has been removed.
Extend captor to be used as a rest matcher
Extend captor to be used as a rest matcher
E.g., support
args = captor()
when(freud).says(*args).thenReturn("Yes.")
assert freud.says("Are", "you", "dreaming?") == "Yes."
assert args.value == ("Are", "you", "dreaming?")
# or
kwargs = captor()
when(freud).does(**kwargs).thenReturn(False)
Added call_captor
call = call_captor()
when(mock).do(call).thenReturn("ok")
mock.do(1, 2, x=3)
assert call.value == ((1, 2), {"x": 3})
Added patch_attr and patch_dict for non-callable monkeypatch-style use cases
(e.g. sys.stdout, sys.argv, and environment/config dictionaries) with
context-manager support and restoration through unstub.
E.g.
patch_attr("sys.argv", ["foo", "bar"])
with patch_attr("sys.stdout", StringIO()) as stdout: ...
with patch_dict(os.environ, {"user": "bob"}): ...
Added explicit partial-unstub targeting by host + attribute name.
This complements method-reference partial unstub (e.g. unstub(cat.meow))
and supports tuple form and shorthand form, including multiple attributes
in one call.
E.g.
unstub(cat.meow)
unstub((cat, "meow"))
unstub(cat, "meow")
unstub((cat, "meow"), (os.path, "exists"))
Also implemented unstub("os.path")
Bug fixes and iteration on the chain feature now supporting deep property chaining as well.
Bug fixes and iteration on the chain feature now supporting deep property chaining as well.
Rollback specificity ordering from a4. Turns out that this less predictable then the last one takes it all rule.
Allow ... in fixed argument positions as an ad-hoc any matcher. Trailing positional ... keeps its existing "rest" semantics.
Allow ... in fixed argument positions as an ad-hoc any matcher.
Trailing positional ... keeps its existing "rest" semantics.
Expanded mock({...}) constructor shorthands. Refer https://mockito-python.readthedocs.io/en/latest/mock-shorthands.html
Added chained stubbing and expectations across call/property hops, e.g.
when(cat).meow().purr().thenReturn(...), when(User).query.filter_by(...).first(), and
expect(cat, times=1).meow().purr(), including cleanup that preserves sibling chain branches.
BREAKING: Stubs for the same method are now sorted by specificity. #110 Rolled back in a5.
Same-ish are for example
when(os.path).exists(...).thenCallOriginalImplementation()
when(os.path).exists('.flake8').thenReturn(False)
Added first-class async/await stubbing support: async callables now preserve awaitable behavior for thenReturn , thenRaise , and thenAnswer (including
Added first-class async/await stubbing support: async callables now preserve
awaitable behavior for thenReturn, thenRaise, and thenAnswer (including
sync and async answer callables), with parity across when, when2,
patch, and expect.
Note that async introspection metadata (e.g. inspect.iscoroutinefunction)
for stub wrappers is currently implemented only on Python 3.12+.
Added first-class property/descriptor stubbing support, including class-level property
stubbing via when(F).p.thenReturn(...) and thenCallOriginalImplementation() support for
property stubs (including chained answers like
thenReturn(...).thenCallOriginalImplementation()). Stubbing instance properties now fails
fast with clear guidance to use class-level stubbing (when(F).p...).
The legacy in-order verification mode ( inorder.verify(...) ) is deprecated in favor of InOrder(...) .
Added a first-class InOrder API via mockito.InOrder (also available as
mockito.inorder.InOrder). The legacy in-order mode only supported one mock at a time;
the new API supports true cross-mock order verification.
Migration (old limited style -> new style)::
# Before (legacy, single-mock order only)
from mockito import inorder
inorder.verify(cat).meow()
inorder.verify(cat).purr()
# Now (preferred, explicit cross-mock order)
from mockito import InOrder
in_order = InOrder(cat, dog)
in_order.verify(cat).meow()
in_order.verify(dog).bark()
The legacy in-order verification mode (inorder.verify(...))
is deprecated in favor of InOrder(...).
Nothing published for this version
Improved behavior of the ad-hoc methods of mocks.
Improved behavior of the ad-hoc methods of mocks. (#92)
Make the shortcut when(mock).foo().thenReturn() officially work and just assume the user forgot the None as return value.
Implement defined behavior for deepcopy for mocks.
Implement defined behavior for deepcopy for mocks. (#91)
Maintenance release adding support for Python 3.13.
Maintenance release adding support for Python 3.13.
Fixed issue (#86) where you couldn't setup expectations for objects or mocks with an overridden __eq__ method.
Fixed issue (#86) where you couldn't setup expectations for objects or mocks with an overridden __eq__ method.
Fixed issue (#82) with methods which have arguments named value or exception.
Fixed issue (#82) with methods which have arguments named value or exception.
@Oracking fixed expect to support a string as its first argument. All other functions supported that already. E.g.
@Oracking fixed expect to support a string as its first argument. All other functions supported that already. E.g.
expect('os.path', times=2).exists(...).thenReturn(True)
@avandierast implemented thenCallOriginalImplementation. See #60
@avandierast implemented thenCallOriginalImplementation. See #60
# Let `os.path.exists` use the real filesystem (often needed when
# the testing framework needs itself a working `os.path.exists`
# implementation) *but* fake a `.flake8` file.
when(os.path).exists(...).thenCallOriginalImplementation()
when(os.path).exists('.flake8').thenReturn(True)
Restore compatibility with Python 2.7
Restore compatibility with Python 2.7
Nothing published for this version
Hotfix: Correctly unstub methods extracted to the module level, for example random.randint() et.al. from the standard library. See #53
Hotfix: Correctly unstub methods extracted to the module level, for example random.randint() et.al. from the standard library. See #53
Let mock(spec=SomeClass) work just as mock(SomeClass)
Let mock(spec=SomeClass) work just as mock(SomeClass)
Reimplement captor to capture only during execution phase of a test.
Reimplement captor to capture only during execution phase of a test.
Teach captor to remember all used values (@shashankrnr32). E.g.
Teach captor to remember all used values (@shashankrnr32). E.g.
arg = captor() mock.do_something(123) mock.do_something(456) verify(mock).do_something(arg) assert arg.all_values == [123, 456]
- Fix typo in spy2 doc
Fix typo in spy2 doc
@nielsvaneck fixed how we can lookup inherited classmethods.
@nielsvaneck fixed how we can lookup inherited classmethods.
Code base now is python 3 compatible. No 2to3 anymore.
Code base now is python 3 compatible. No 2to3 anymore.
Fine tune error messages on unexpected calls or verifications. E.g. if you expect when(dog).bark('Wuff') but on call time do dog.bark('Wufff'). Likewise, if you call dog.bark('Miau') and then verify(dog).bark('Maui').
@felixonmars fixed a small compatibility issue with python 3.8
Mocking properties has become a bit easier. (#26) E.g.
prop = mock()
when(prop).__get__(...).thenReturn(23)
m = mock({'name': prop})
Fix: The context manager (with) has now a proper implementation
Fix: The context manager (with) has now a proper implementation
Fix: Calling patch with two arguments can now be used with with
Fix: Do not treat the placeholder arguments (Ellipsis, args, kwargs) as special on call time anymore. (T.i. they only have a meaning when stubbing or verifying.)
Enhancement: Changed some truthy or equality tests to identity (is) tests. This reduces edge-cases where some user object defines __eq__ or __bool__. (Hello _numpy_!)
Added forget_invocations function. Thanks to @maximkulkin
Added forget_invocations function. Thanks to @maximkulkin
This is generally useful if you already call mocks during your setup routine. Now you could 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.
Better error messages for failed verifications. By @lwoydziak
Better error messages for failed verifications. By @lwoydziak
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
verifyZeroInteractions implemented. This is actually a *breaking change*, because verifyZeroInteractions was an alias for verifyNoMoreInteractions (si…
verifyZeroInteractions implemented. This is actually a breaking change, because verifyZeroInteractions was an alias for verifyNoMoreInteractions (sic!). If you used it, just call the other function.
verifyStubbedInvocationsAreUsed implemented. This is meant to be called right before an unstub and should improve long time maintenance. It doesn't help during design time. Note that pytest-mockito automatically calls this for you.
All verify* functions now warn you if you pass in an object which was never stubbed.
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
But if you did, we do not export Mock anymore. Mock has been deprecated long ago and is now for internal use only. You must use mock.
This is a major update; mostly because of internal code reorganization (imports) it cannot be guaranteed that this will not break for you. Though if you just used the public API you should be fine. None of the vintage old tests have been removed and they at least pass.
In general unclassified imports (from mocktio import *) are not recommended. But if you did, we do not export Mock anymore. Mock has been deprecated long ago and is now for internal use only. You must use mock.
Another important change is, that mockito's strict mode is far more strict than before. We now generally try to match the signature of the target method with your usage. Usually this should help you find bugs in your code, because it will make it easier to spot changing interfaces.
mock, when, verify return mostly empty objects. It is unlikely to have a method_name clash.
Specced mocks instance = mock(Class) will pass isinstance tests like isinstance(instance, Class)
For when and verify the function signature or argument matchers can be greatly simplified. E.g. when(requests).get(...).thenReturn('OK') will match any argument you pass in. There are args and kwargs matchers as well. So when(requests).get('https://...', **kwargs).thenReturn(...) will make an exact match on the first argument, the url, and ignore all the headers and other stuff.
Mocks can be preconfigured: mock({'text': 'OK'}). For specced mocks this would be e.g. mock({'text': 'OK'}, spec=requests.Response).
If you mock or patch an object, the function signatures will be matched. So:
def foo(a, b=1): ... when(main).foo(12) # will pass when(main).foo(c=13) # will raise immediately
Mock Dummies are now callable:
m = mock() m(1, 2) verify(m).__call__(...)
Mock() is now an implementation detail; it is not exported anymore. Use mock().
You can unstub individual patched objects unstub(obj). (Before it was all or nothing.)
Added basic context manager support when using when. Note that verify has to be called within the with context.
with when(rex).waggle().thenReturn('Yup'):
assert rex.waggle() == 'Yup'
verify(rex).waggle()
Aliased any_ to ANY, args to ARGS and kwargs to KWARGS. You can use python's builtin any as a stand in for ANY.
As a convenience you can use our any_ matcher like a type instead of any_():
dummy(1) verify(dummy).__call__(ANY)
Added when2, expect, spy2
Make the mocked function (replacement) more inspectable. Copy __doc__, __name__ etc.
You can configure magic methods on mocks:
dummy = mock() when(dummy).__getitem__(1).thenReturn(2) assert dummy[1] == 2
Nothing published for this version
Fix: Allow verifyNoMoreInteractions call for real (stubbed) objects
Fix: Allow verifyNoMoreInteractions call for real (stubbed) objects
Added a ton of new argument matchers. Namely::
Added a ton of new argument matchers. Namely:
'and_', 'or_', 'not_', 'eq', 'neq', 'lt', 'lte', 'gt', 'gte', 'arg_that', 'matches', 'captor'
Aliases any matcher to any_ because it's a builtin.
Fixes an issue where mockito could not correctly verify your function invocations, if you grabbed a method from its object and used it ('detached') as a plain function:
m = mock() f = m.foo # detach f(1, 2) # pass it around and use it like a function f(2, 3) verify(m).foo(...) # finally verify interactions
Thank you @maximkulkin
Added thenAnswer(callable). The callable will be called to compute the answer the stubbed method will return. For that it will receive the arguments o
Added thenAnswer(callable). The callable will be called to compute the answer the stubbed method will return. For that it will receive the arguments of the caller:
m = mock() when(m).do_times(any(), any()).thenAnswer(lambda one, two: one * two) self.assertEquals(20, m.do_times(5, 4))
Thank you @stubbsd
BREAKING CHANGE: Throw early when calling not expected methods in strict mode.
Print keyword arguments nicely.
Be very forgiving about return values and assume None as default. T.i. when(Dog).bark('Miau').thenReturn() is enough to return None.
Make keyword argument order unimportant.
BREAKING CHANGE: Throw early when calling not expected methods in strict mode.
Remove hard coded distribute setup files.
Remove hard coded distribute setup files.
Nothing published for this version
Fixed issue #9 [http://bitbucket.org/szczepiq/mockito-python/issue/9] : Generating stubs from classes caused method to be replaced in original classes
Fixed issue #9 [http://bitbucket.org/szczepiq/mockito-python/issue/9] : Generating stubs from classes caused method to be replaced in original classes.
Deprecated APIs now generate deprecation warnings.
Added possibility to spy on real objects.
Added "never" syntactic sugar for verifications.
Fixed issue with named arguments matching.
Python 2.7 support
Deprecated APIs now generate deprecation warnings.
Added possibility to verify invocations in order.
Added possibility to verify invocations in order.
Fixed issue with installing mockito from egg without distribute installed.
Fixed annoying issue #8 [http://bitbucket.org/szczepiq/mockito-python/issue/8]
Bug-fix release.
Fixed annoying issue #8 [http://bitbucket.org/szczepiq/mockito-python/issue/8]
Renamed mock creation method from "Mock" (upper "M") to "mock". Old name stays for compatibility until 1.0 release. Other Changes:
Renamed mock creation method from "Mock" (upper "M") to "mock". Old name stays for compatibility until 1.0 release.
Official Python3 support via distutils + 2to3.
Renamed mock creation method from “Mock” (upper “M”) to “mock”. Old name stays for compatibility until 1.0 release.
Official Python3 support via distutils + 2to3.
On this page
MOCKITO CHANGE LOG
Release 2.0.0 (March 10, 2026)
Release 1.5.5 (November 17, 2025)
Release 1.5.4 (January 22, 2025)
Release 1.5.3 (November 9, 2024)
Release 1.5.2 (November 6, 2024)
Release 1.5.1 (September 4, 2024)
Release 1.5.0 (March 4, 2024)
Release 1.4.0 (August 25, 2022)
Release 1.3.5 (August 18, 2022)
Release 1.3.3 (June 23, 2022)
Release 1.3.2 (June 23, 2022)
Release 1.3.1 (June 14, 2022)
Release 1.3.0 (December 3, 2021)
Release 1.2.2 (September 9, 2020)
Release 1.2.1 (February 19, 2020)
Release 1.2.0 (November 25, 2019)
Release 1.1.1 (August 28, 2018)
Release 1.1.0 (May 2, 2018)
Release 1.0.12 (June 3, 2017)
Release 1.0.7 - 1.0.10 (January 31 - February 2, 2017)
Release 1.0.0 - 1.0.5 (January 24 - 27, 2017)
Release 0.7.1 (December 27, 2016)
Release 0.7.0 (July 15, 2016)
Release 0.6.1 (May 20, 2016)
Release 0.6.0 (April 25, 2016)
Release 0.5.3 (April 23, 2016)
Release 0.5.1 (August 4, 2010)
Release 0.5.0 (July 26, 2010)
Release 0.4.0 (July 2, 2010)
Release 0.3.1
Release 0.3.0
Nothing published for this version
Your coding agent can read these notes before it upgrades. Set up the MCP server →