SyntaxStudy
Sign Up
Python Mocking with unittest.mock
Python Intermediate 4 min read

Mocking with unittest.mock

unittest.mock

unittest.mock patches dependencies so tests run without real I/O, network, or database calls.

Example
from unittest.mock import patch, MagicMock

def test_sends_email():
    with patch("myapp.services.send_email") as mock_send:
        mock_send.return_value = True
        result = register_user("alice@example.com")
        mock_send.assert_called_once_with("alice@example.com", subject="Welcome")
        assert result["status"] == "ok"

@patch("myapp.api.requests.get")
def test_fetch_user(mock_get):
    mock_get.return_value = MagicMock(status_code=200)
    mock_get.return_value.json.return_value = {"id": 1, "name": "Alice"}
    user = fetch_user(1)
    assert user["name"] == "Alice"
Pro Tip

Patch the name as imported, not where defined: patch("myapp.views.requests.get") not "requests.get".