Skip to content

Mocking and Patching with unittest.mock

Why mock?

You mock when a dependency is:

  • slow
  • flaky
  • external (network, API)
  • expensive to set up

Example: patch a function call

service.py
import requests
 
 
def fetch_status(url: str) -> int:
    return requests.get(url, timeout=10).status_code
service.py
import requests
 
 
def fetch_status(url: str) -> int:
    return requests.get(url, timeout=10).status_code
test_service.py
from unittest.mock import patch
 
import service
 
 
def test_fetch_status_mocked():
    with patch("service.requests.get") as get:
        get.return_value.status_code = 200
        assert service.fetch_status("https://example.com") == 200
test_service.py
from unittest.mock import patch
 
import service
 
 
def test_fetch_status_mocked():
    with patch("service.requests.get") as get:
        get.return_value.status_code = 200
        assert service.fetch_status("https://example.com") == 200

Using autospec

autospec=Trueautospec=True helps match real signatures.

patch_autospec.py
from unittest.mock import patch
 
 
def sample(a, b):
    return a + b
 
 
with patch("__main__.sample", autospec=True) as fn:
    fn.return_value = 10
    assert sample(1, 2) == 10
patch_autospec.py
from unittest.mock import patch
 
 
def sample(a, b):
    return a + b
 
 
with patch("__main__.sample", autospec=True) as fn:
    fn.return_value = 10
    assert sample(1, 2) == 10

Tips

  • mock at the import location used by the code under test
  • keep mocks minimal; prefer real unit logic

If this helped you, consider buying me a coffee ☕

Buy me a coffee

Was this page helpful?

Let us know how we did