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 |