Mockito for Python
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.
Warnings
- breaking Several 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.
- breaking Context 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.
- deprecated The functions `verifyNoMoreInteractions`, `verifyNoUnwantedInteractions`, and the limited `inorder.verify(...)` mode are deprecated in favor of their renamed or enhanced counterparts.
- gotcha It 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.
- gotcha By 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.
- gotcha Mockito'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.
Install
-
pip install mockito
Imports
- 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
- Mock (uppercase)
from mockito import mock
Quickstart
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!")