{"id":3554,"library":"mockito","title":"Mockito for Python","description":"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.","status":"active","version":"2.0.3","language":"en","source_language":"en","source_url":"https://github.com/kaste/mockito-python","tags":["mocking","testing","unit-testing","stubbing","spying","test-doubles"],"install":[{"cmd":"pip install mockito","lang":"bash","label":"Install stable version"}],"dependencies":[{"reason":"Convenience plugin providing fixtures for automatic cleanup (unstub) and verification when using pytest.","package":"pytest-mockito","optional":true}],"imports":[{"symbol":"when","correct":"from mockito import when"},{"symbol":"mock","correct":"from mockito import mock"},{"symbol":"unstub","correct":"from mockito import unstub"},{"symbol":"verify","correct":"from mockito import verify"},{"symbol":"expect","correct":"from mockito import expect"},{"symbol":"InOrder","correct":"from mockito import InOrder"},{"symbol":"patch_attr","correct":"from mockito import patch_attr"},{"symbol":"patch_dict","correct":"from mockito import patch_dict"},{"note":"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.","wrong":"from mockito import *","symbol":"* (wildcard import)","correct":"from mockito import when, mock, unstub"},{"note":"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.","wrong":"from mockito import Mock","symbol":"Mock (uppercase)","correct":"from mockito import mock"}],"quickstart":{"code":"import os\nfrom mockito import when, mock, unstub, verify\n\nclass MyService:\n    def get_file_content(self, path):\n        if os.path.exists(path):\n            # In a real scenario, this would read from the file system\n            return f\"Content of {path}\"\n        return None\n\n    def fetch_data_from_api(self, url):\n        # Imagine 'requests' is a dependency that makes HTTP calls\n        import requests # Imported locally for example, usually at top\n        try:\n            response = requests.get(url)\n            response.raise_for_status() # Raise an HTTPError for bad responses (4xx or 5xx)\n            return response.text\n        except Exception:\n            return \"Error fetching data\"\n\n# --- Test MyService with Mockito ---\n\n# Scenario 1: Mocking a module function (os.path.exists)\ndef test_get_file_content_exists():\n    service = MyService()\n    when(os.path).exists('/foo').thenReturn(True)\n    content = service.get_file_content('/foo')\n    assert content == \"Content of /foo\"\n    verify(os.path).exists('/foo')\n    unstub()\n\ndef test_get_file_content_not_exists():\n    service = MyService()\n    when(os.path).exists('/bar').thenReturn(False)\n    content = service.get_file_content('/bar')\n    assert content is None\n    verify(os.path).exists('/bar')\n    unstub()\n\n# Scenario 2: Mocking a third-party library (requests)\ndef test_fetch_data_success():\n    service = MyService()\n    import requests # Ensure requests is available or mocked correctly\n    \n    # Create a mock response object\n    mock_response = mock({'status_code': 200, 'text': '{\"data\": \"mocked data\"}'})\n    when(requests).get('http://example.com/api').thenReturn(mock_response)\n    \n    data = service.fetch_data_from_api('http://example.com/api')\n    assert data == '{\"data\": \"mocked data\"}'\n    verify(requests).get('http://example.com/api')\n    unstub()\n\ndef test_fetch_data_failure():\n    service = MyService()\n    import requests\n    \n    # Mock requests.get to raise an exception\n    when(requests).get('http://bad.com/api').thenRaise(requests.exceptions.ConnectionError)\n    \n    data = service.fetch_data_from_api('http://bad.com/api')\n    assert data == \"Error fetching data\"\n    verify(requests).get('http://bad.com/api')\n    unstub()\n\n# Run tests (example usage)\nprint(\"Running Mockito quickstart tests...\")\ntest_get_file_content_exists()\ntest_get_file_content_not_exists()\ntest_fetch_data_success()\ntest_fetch_data_failure()\nprint(\"All Mockito quickstart tests passed!\")","lang":"python","description":"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."},"warnings":[{"fix":"Update calls to the new function names: `ensureNoUnverifiedInteractions`, `verifyExpectedInteractions`, and use `InOrder(...)` for ordered verification.","message":"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.","severity":"breaking","affected_versions":"2.0.0 and later"},{"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'.","message":"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.","severity":"breaking","affected_versions":"2.0.0 and later"},{"fix":"Migrate to `ensureNoUnverifiedInteractions`, `verifyExpectedInteractions`, and the `InOrder(...)` API for future compatibility and improved semantics.","message":"The functions `verifyNoMoreInteractions`, `verifyNoUnwantedInteractions`, and the limited `inorder.verify(...)` mode are deprecated in favor of their renamed or enhanced counterparts.","severity":"deprecated","affected_versions":"2.0.0 and later"},{"fix":"Always include `unstub()` in your test teardown (e.g., `tearDown` in `unittest.TestCase` or use `pytest-mockito` fixtures for automatic handling).","message":"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.","severity":"gotcha","affected_versions":"All versions"},{"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).","message":"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.","severity":"gotcha","affected_versions":"All versions"},{"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`.","message":"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.","severity":"gotcha","affected_versions":"2.0.0 and later"}],"env_vars":null,"last_verified":"2026-04-11T00:00:00.000Z","next_check":"2026-07-10T00:00:00.000Z"}