unittest.mock.patch in PyTest - Build an Automation Script
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.
Now add data-driven testing with 3 different mocked API responses and verify process_data handles each correctly