Mocking replaces real objects with fake implementations to isolate code under test.
1from unittest.mock import patch, MagicMock, AsyncMock2import pytest34# Mocking a function5@patch("mymodule.requests.get")6def test_fetch_data(mock_get):7 mock_get.return_value.json.return_value = {"data": "test"}8 mock_get.return_value.status_code = 200910 result = fetch_data("https://api.example.com")11 assert result == {"data": "test"}12 mock_get.assert_called_once_with("https://api.example.com")1314# Mocking class methods15@patch("mymodule.Database")16def test_save_user(mock_db):17 mock_instance = mock_db.return_value18 mock_instance.save.return_value = True1920 user = save_user(name="Alice")21 mock_instance.save.assert_called_once()2223# Async mocking24@patch("mymodule.async_fetch", new_callable=AsyncMock)25async def test_async_operation(mock_fetch):26 mock_fetch.return_value = "result"27 result = await async_operation()28 assert result == "result"2930# MagicMock for complex objects31mock_obj = MagicMock()32mock_obj.method.return_value = 4233print(mock_obj.method()) # 4234print(mock_obj.method.called) # True
When to mock: