0
0
PyTesttesting~15 mins

unittest.mock.patch in PyTest - Build an Automation Script

Choose your learning style9 modes available
Test function behavior using unittest.mock.patch to mock a dependency
Preconditions (2)
Step 1: Use unittest.mock.patch to mock 'requests.get' inside the test
Step 2: Set the mock to return a response object with .json() method returning {'key': 'value'}
Step 3: Call 'process_data' function
Step 4: Verify that 'process_data' returns the expected processed result based on the mocked data
✅ Expected Result: The test passes confirming that 'process_data' correctly processes the mocked API data without making a real HTTP request
Automation Requirements - pytest
Assertions Needed:
Assert that 'process_data' returns the expected processed output
Assert that 'requests.get' was called once with the correct URL
Best Practices:
Use unittest.mock.patch as a context manager or decorator to mock external dependencies
Mock only the external call, not the function under test
Use mock return_value and side_effect properly to simulate responses
Keep tests isolated and independent from real network calls
Automated Solution
PyTest
import pytest
from unittest.mock import patch, Mock

# Assume these are in your module named 'my_module'
import my_module

def test_process_data_with_mocked_get():
    mock_response = Mock()
    mock_response.json.return_value = {'key': 'value'}

    with patch('my_module.requests.get', return_value=mock_response) as mock_get:
        result = my_module.process_data()

        # Assert the processed result is as expected
        assert result == 'Processed value', f"Expected 'Processed value' but got {result}"

        # Assert requests.get was called once with the expected URL
        mock_get.assert_called_once_with('https://api.example.com/data')

This test uses unittest.mock.patch as a context manager to replace requests.get with a mock object during the test. We create a mock response object whose json() method returns a fixed dictionary. This simulates the API response without making a real HTTP call.

We then call process_data(), which internally calls get_data() that uses requests.get. Because of the patch, it receives the mocked response.

We assert that the processed result matches the expected output based on the mocked data. We also verify that requests.get was called exactly once with the correct URL, ensuring our code calls the API as expected.

This approach keeps tests fast, reliable, and independent from external services.

Common Mistakes - 4 Pitfalls
Mocking the function under test instead of its dependencies
{'mistake': "Not setting the mock's return_value or side_effect properly", 'why_bad': 'The function under test may receive None or unexpected values, causing test failures or false positives.', 'correct_approach': 'Always configure the mock to return realistic data matching what the real dependency would return.'}
Using hardcoded patch target strings incorrectly
{'mistake': 'Not asserting that the mock was called', 'why_bad': 'You might miss that the function did not call the dependency as expected.', 'correct_approach': "Use mock's assert_called_once_with or similar methods to verify calls."}
Bonus Challenge

Now add data-driven testing with 3 different mocked API responses and verify process_data handles each correctly

Show Hint