Test Overview
This test checks how mocking helps isolate the code under test by replacing a real dependency with a mock object. It verifies that the function behaves correctly when the dependency returns a controlled value.
This test checks how mocking helps isolate the code under test by replacing a real dependency with a mock object. It verifies that the function behaves correctly when the dependency returns a controlled value.
import pytest from unittest.mock import Mock def fetch_data(api_client): response = api_client.get_data() return response['value'] * 2 def test_fetch_data_with_mock(): mock_api_client = Mock() mock_api_client.get_data.return_value = {'value': 10} result = fetch_data(mock_api_client) assert result == 20
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | Test environment is ready with pytest and unittest.mock imported | — | PASS |
| 2 | Creates a mock object to replace the real api_client | mock_api_client is a Mock instance with get_data method mocked | — | PASS |
| 3 | Sets mock_api_client.get_data to return {'value': 10} | Calling mock_api_client.get_data() returns {'value': 10} | — | PASS |
| 4 | Calls fetch_data with mock_api_client | fetch_data calls mock_api_client.get_data(), receives {'value': 10} | Result should be 10 * 2 = 20 | PASS |
| 5 | Asserts that result equals 20 | Result is 20 as expected | assert result == 20 | PASS |
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