Mocking is a testing technique in which a real dependency, such as a database, an HTTP service or the system clock, is replaced by a controlled stand-in. The mock returns scripted responses and can record how it was called, so a test can check behavior without relying on the real thing.
Why it matters
Mocks make unit tests fast, deterministic and independent of the network. They let you simulate rare conditions that are hard to trigger for real, such as a payment gateway timing out or a disk being full. The risk is over-mocking: if a mock does not behave like the real system, tests pass while production fails, and tests tied to exact calls break whenever the implementation changes. Related terms include stubs (canned answers), fakes (simple working versions) and spies (record calls).
Example
from unittest.mock import Mock
http = Mock()
http.get.return_value.status_code = 503
assert check_site("https://example.com", http) == "down"
http.get.assert_called_once_with("https://example.com")
No network request is made, yet the failure path is verified.
Common mistakes
- Mocking the code under test instead of its dependencies.
- Asserting on every internal call, making tests brittle.
- Never running tests against the real dependency in integration tests.
Related
Get notified when this term updates
Plus occasional practical tips on uptime and monitoring, nothing else. Unsubscribe anytime.
This page is general information written by our editorial team and updated when documentation changes. Servers and providers differ, so test changes safely first. See our editorial policy and disclaimer.