Skip to main content
Albero Academy

Mocking

Isolate code under test by faking its dependencies.

Testing9 min

A good unit test is fast and deterministic — but real dependencies (a network API, a database, the current time) are slow and unpredictable. Mocking replaces them with controllable fakes, so you test your logic in isolation.

Patching a dependency

patch temporarily swaps a real object for a Mock; return_value scripts what the fake returns:

unittest.mock
from unittest.mock import patch
def get_user(client, uid):
return client.fetch(uid)["name"]
@patch("myapp.api_client")
def test_get_user(mock_client):
mock_client.fetch.return_value = {"name": "Ana"} # script the fake
assert get_user(mock_client, 1) == "Ana" # no real network call
mock_client.fetch.assert_called_once_with(1) # verify the interaction

Scripting behaviour

  • return_value — a fixed result the mock returns.
  • side_effect — raise an exception, or return different values on successive calls (great for testing error handling).
  • assert_called_with — verify the mock was called correctly.

Key takeaways

  1. 01Mocks replace real dependencies with controllable fakes for fast, isolated tests.
  2. 02patch swaps an object for a Mock for the duration of a test.
  3. 03return_value fixes the result; side_effect raises errors or varies per call.
  4. 04assert_called_with verifies how the dependency was used.
  5. 05Mock slow/external/non-deterministic things — but don't over-mock your own logic.

Finished this chapter?

Mark it complete to track your progress through Python.