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:
from unittest.mock import patchdef 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 fakeassert get_user(mock_client, 1) == "Ana" # no real network callmock_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
- 01Mocks replace real dependencies with controllable fakes for fast, isolated tests.
- 02patch swaps an object for a Mock for the duration of a test.
- 03return_value fixes the result; side_effect raises errors or varies per call.
- 04assert_called_with verifies how the dependency was used.
- 05Mock slow/external/non-deterministic things — but don't over-mock your own logic.
