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
muslpy 3.10–3.95 runs
installs and imports cleanly · install 0.0s · import 0.066s · 18.1MB
glibcpy 3.10–3.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!")
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'mockito'
The 'mockito' library is not installed in the Python environment.
fixInstall 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'.
fixUse 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.
fixEnsure '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.
fixAdjust 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.
fixEnsure 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.