Mockito for Python

2.0.3 · active · verified Sat Apr 11

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

Install

Imports

Quickstart

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!")

view raw JSON →