Registry / testing / mockito

mockito

JSON →
library2.0.4pypypi✓ verified 23d ago

Mockito is a spying framework for Python, based on the Java library of the same name. It focuses on an ergonomic API for stubbing and verification in unit tests, aiming for clear and readable test code. The current version is 2.0.3, and it maintains an active release cadence with continuous development and updates.

pip install mockito
INSTALL
IMPORT
SIG · MOCKITO
M
mockito
testingpythonv2.0.4
Install
1.6s avg
Import
62ms
Disk
16MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v2.0.4 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.066s · 18.1MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 1.6s · import 0.058s · 19MB
16MB installed
● package 16MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

when
from mockito import when
mock
from mockito import mock
unstub
from mockito import unstub
verify
from mockito import verify
expect
from mockito import expect
InOrder
from mockito import InOrder
patch_attr
from mockito import patch_attr
patch_dict
from mockito import patch_dict
* (wildcard import)
from mockito import when, mock, unstub
from mockito import *
Wildcard imports are generally discouraged and specifically for Mockito v1.0.0 and later, the `Mock` (uppercase) class is no longer exported, which can lead to unexpected errors if relied upon.
Mock (uppercase)
from mockito import mock
from mockito import Mock
The uppercase `Mock` class has been deprecated and is for internal use only since v1.0.0. Use the lowercase `mock` function for creating mock objects.

This quickstart demonstrates how to use Mockito to stub module-level functions (like `os.path.exists`) and third-party library calls (like `requests.get`). It covers returning specific values, raising exceptions, and verifying interactions, always remembering to call `unstub()` to clean up mocks after each test.

import os from mockito import when, mock, unstub, verify class MyService: def get_file_content(self, path): if os.path.exists(path): # In a real scenario, this would read from the file system return f"Content of {path}" return None def fetch_data_from_api(self, url): # Imagine 'requests' is a dependency that makes HTTP calls import requests # Imported locally for example, usually at top try: response = requests.get(url) response.raise_for_status() # Raise an HTTPError for bad responses (4xx or 5xx) return response.text except Exception: return "Error fetching data" # --- Test MyService with Mockito --- # Scenario 1: Mocking a module function (os.path.exists) def test_get_file_content_exists(): service = MyService() when(os.path).exists('/foo').thenReturn(True) content = service.get_file_content('/foo') assert content == "Content of /foo" verify(os.path).exists('/foo') unstub() def test_get_file_content_not_exists(): service = MyService() when(os.path).exists('/bar').thenReturn(False) content = service.get_file_content('/bar') assert content is None verify(os.path).exists('/bar') unstub() # Scenario 2: Mocking a third-party library (requests) def test_fetch_data_success(): service = MyService() import requests # Ensure requests is available or mocked correctly # Create a mock response object mock_response = mock({'status_code': 200, 'text': '{"data": "mocked data"}'}) when(requests).get('http://example.com/api').thenReturn(mock_response) data = service.fetch_data_from_api('http://example.com/api') assert data == '{"data": "mocked data"}' verify(requests).get('http://example.com/api') unstub() def test_fetch_data_failure(): service = MyService() import requests # Mock requests.get to raise an exception when(requests).get('http://bad.com/api').thenRaise(requests.exceptions.ConnectionError) data = service.fetch_data_from_api('http://bad.com/api') assert data == "Error fetching data" verify(requests).get('http://bad.com/api') unstub() # Run tests (example usage) print("Running Mockito quickstart tests...") test_get_file_content_exists() test_get_file_content_not_exists() test_fetch_data_success() test_fetch_data_failure() print("All Mockito quickstart tests passed!")
Debug
Known issues
breakingSeveral verification functions were renamed in v2.x for clarity. `verifyNoMoreInteractions` is now `ensureNoUnverifiedInteractions`, and `verifyNoUnwantedInteractions` is now `verifyExpectedInteractions`. The legacy `inorder.verify(...)` has been replaced by a more robust `InOrder(...)` API for cross-mock verification.
fix
Update calls to the new function names: `ensureNoUnverifiedInteractions`, `verifyExpectedInteractions`, and use `InOrder(...)` for ordered verification.
affects: 2.0.0 and later
breakingContext managers (e.g., `with when(...)`) in v2.x now automatically check usage and explicit expectations (set via `expect`) on exit. This can cause `UnnecessaryStubbingException` if stubs are defined but not used.
fix
Ensure all stubs defined within a context manager are actually invoked in the test. If intentional, this check can be disabled by setting the environment variable `MOCKITO_CONTEXT_MANAGERS_CHECK_USAGE` to '0'.
affects: 2.0.0 and later
deprecatedThe functions `verifyNoMoreInteractions`, `verifyNoUnwantedInteractions`, and the limited `inorder.verify(...)` mode are deprecated in favor of their renamed or enhanced counterparts.
fix
Migrate to `ensureNoUnverifiedInteractions`, `verifyExpectedInteractions`, and the `InOrder(...)` API for future compatibility and improved semantics.
affects: 2.0.0 and later
gotchaIt is crucial to call `unstub()` after each test that uses Mockito's `when()` or `patch_*` functions to prevent mocks from leaking into other tests and causing flaky results.
fix
Always include `unstub()` in your test teardown (e.g., `tearDown` in `unittest.TestCase` or use `pytest-mockito` fixtures for automatic handling).
affects: All versions
gotchaBy default, `mock()` objects are not 'strict'. This means unstubbed methods will return `None` without an error. If `mock(strict=True)` is used, any unexpected (unstubbed) interactions will raise an error immediately.
fix
Decide on strictness based on your testing philosophy. For robust tests that fail on unexpected calls, use `mock(strict=True)` or `mock(spec=YourClass)` (which implies strictness).
affects: All versions
gotchaMockito's `any()` matchers in v2.x, similar to Java Mockito 2.x, do not accept `None` (null) values by default. Passing `None` to `any(SomeClass)` might fail if the mock expects a non-null object.
fix
If `None` is an expected argument, explicitly match it with `None` or consider using more specific argument matchers if applicable. For Java Mockito, `Mockito.<Type>any()` is used, but Python Mockito's behavior is often managed by the specific matchers or explicit `None`.
affects: 2.0.0 and later
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'mockito'
The 'mockito' library is not installed in the Python environment.
fix
Install the 'mockito' library using pip: 'pip install mockito'.
AttributeError: module 'mockito' has no attribute 'when'
Incorrect import statement; 'when' should be imported directly from 'mockito'.
fix
Use the correct import: 'from mockito import when'.
TypeError: when() missing 1 required positional argument: 'method'
The 'when' function is called without specifying the method to stub.
fix
Ensure 'when' is called with the method to be stubbed: 'when(SomeClass).some_method().thenReturn(value)'.
VerificationError: Wanted times: 0, actual times: 1
A method was called more times than specified in the verification step.
fix
Adjust the verification to match the actual number of calls: 'verify(mocked_object, times=1).method()'.
UnfinishedStubbingException: Unfinished stubbing detected
A stubbing setup was not completed properly, leaving an unfinished stubbing.
fix
Ensure all stubbing setups are completed with a return value or exception: 'when(mocked_object).method().thenReturn(value)'.
Upgrade
Version history
2.0.4latest on PyPI · released Apr 15, 2026
Audit
Dependencies
pytest-mockitooptionalConvenience plugin providing fixtures for automatic cleanup (unstub) and verification when using pytest.
Agent activity
5 hits · last 30 days
node
4
Resources