Test function behavior with mocked dependency
Preconditions (2)
✅ Expected Result: The function under test returns the expected result using the mock, and no real external calls happen
from unittest.mock import patch import pytest # Function that depends on an external service def get_data_from_service(): # Imagine this calls an external API raise NotImplementedError("External service call") def process_data(): data = get_data_from_service() return data.upper() # Test function with mocking @patch('__main__.get_data_from_service') def test_process_data_with_mock(mock_get): # Arrange: set mock return value mock_get.return_value = 'mocked data' # Act: call function under test result = process_data() # Assert: check result uses mocked data assert result == 'MOCKED DATA' # Assert: mock was called once mock_get.assert_called_once() if __name__ == '__main__': pytest.main([__file__])
The get_data_from_service function simulates an external call that we do not want to run during tests.
We use @patch to replace get_data_from_service with a mock that returns a fixed string.
This isolates process_data from the real external call, so the test is fast and reliable.
Assertions check that the output uses the mocked data and that the mock was called exactly once.
Now add data-driven testing with 3 different mock return values and expected outputs
get_data in pytest using the monkeypatch fixture?setattr with the target path and replacement function.monkeypatch.setattr('module.get_data', lambda: 'mocked'), which correctly mocks the function.import pytest
def fetch_data():
return 'real data'
def process():
return fetch_data()
def test_process(monkeypatch):
monkeypatch.setattr('__main__.fetch_data', lambda: 'mocked data')
result = process()
assert result == 'mocked data'
print(result)fetch_data with a lambda returning 'mocked data'.process() calls fetch_data(), it gets 'mocked data' instead of 'real data'.def get_value():
return 10
def test_value(monkeypatch):
monkeypatch.setattr('__main__.get_value', lambda: 20)
assert get_value() == 10get_value to return 20 instead of 10.send_email() that sends real emails. You want to test notify_user() which calls send_email()</>. How does mocking send_email() help isolate notify_user() in pytest?send_email() during tests can send unwanted emails and slow tests.send_email() replaces it with a fake that does nothing or simulates success, isolating notify_user() logic.Pass the test and this pattern moves unknown