0
0
PyTesttesting~15 mins

Mock and MagicMock in PyTest - Build an Automation Script

Choose your learning style9 modes available
Automate testing a function using MagicMock to mock a dependency
Preconditions (2)
Step 1: Create a function 'get_data' that calls an external API function 'fetch_api_data'.
Step 2: Mock 'fetch_api_data' using MagicMock to return a fixed dictionary {'key': 'value'}.
Step 3: Call 'get_data' and verify it returns the mocked dictionary.
Step 4: Verify that 'fetch_api_data' was called exactly once during the test.
✅ Expected Result: The test passes confirming 'get_data' returns the mocked data and 'fetch_api_data' was called once.
Automation Requirements - pytest with unittest.mock
Assertions Needed:
Assert that the return value of 'get_data' matches the mocked dictionary
Assert that the mocked 'fetch_api_data' was called exactly once
Best Practices:
Use MagicMock to mock dependencies
Use patch decorator or context manager to replace the real function
Use assert_called_once() to verify call count
Keep test isolated from real external calls
Automated Solution
PyTest
from unittest.mock import MagicMock, patch
import pytest

# Module code to test
def fetch_api_data():
    # Imagine this calls an external API
    return {'real': 'data'}

def get_data():
    return fetch_api_data()

# Test code
def test_get_data_with_mock():
    with patch('__main__.fetch_api_data', new=MagicMock(return_value={'key': 'value'})) as mock_fetch:
        result = get_data()
        assert result == {'key': 'value'}, f"Expected mocked data, got {result}"
        mock_fetch.assert_called_once()

The test uses patch as a context manager to replace fetch_api_data with a MagicMock that returns a fixed dictionary.

Calling get_data() then returns the mocked data instead of calling the real API.

Assertions check that the returned data matches the mock and that the mocked function was called exactly once.

This keeps the test isolated and fast without real API calls.

Common Mistakes - 3 Pitfalls
Not using patch to replace the real function, so the real API call runs during the test
Using MagicMock without setting return_value, so the mock returns another MagicMock instead of expected data
Not verifying that the mocked function was called, missing important behavior checks
Bonus Challenge

Now add data-driven testing with 3 different mocked return values for 'fetch_api_data' and verify 'get_data' returns each correctly.

Show Hint