Codectionary / Developer documentation / Python

Testing Collaborators with Mock

unittest.mock replaces a collaborator with a configurable object and records calls. It helps test how code coordinates work without a live external service. Run as a Python 3.11+ script.

Syntax

Mock(return_value=value); mock.assert_called_once_with(arguments)

Examples

Testing Collaborators with Mock

Run as a Python 3.11+ script.

from unittest.mock import Mock
def checkout(total, charge):
    return charge(total, currency="GBP")
charge = Mock(return_value="receipt-7")
print(checkout(12, charge))
charge.assert_called_once_with(12, currency="GBP")
print(charge.call_count)
  1. Expected output: receipt-7 1
  2. Dependency injection makes the payment boundary explicit. The assertion verifies both the amount and currency without performing a payment.

Best practices

  • Mock external boundaries rather than every internal implementation detail.
  • Use spec or autospec when a real interface is available to catch misspelled methods.

Runtime & versions

Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Python language reference

Specifications & further reading