What if you could control any external call in your tests like a magic remote control?
Why Mock return values and side effects in PyTest? - Purpose & Use Cases
Imagine testing a function that calls an external service, like fetching weather data. Manually, you have to wait for the real service every time, which is slow and unreliable.
Manually testing with real services is slow, can fail due to network issues, and makes tests flaky. It's hard to test all scenarios, like errors or special responses, because you can't control the real service.
Using mock return values and side effects lets you pretend the external service responds instantly with exactly what you want. You can simulate success, errors, or delays easily, making tests fast, reliable, and thorough.
def test_weather(): data = get_real_weather() assert data['temp'] > 0
from unittest.mock import Mock mock_service = Mock() mock_service.get_weather.return_value = {'temp': 20} assert mock_service.get_weather()['temp'] > 0
It enables fast, reliable tests that cover all cases by controlling what external calls return or do.
Testing a payment system where you mock the bank API to simulate success, failure, or timeout without real money transfers.
Manual testing with real dependencies is slow and unreliable.
Mocking return values and side effects simulates external calls easily.
This makes tests faster, stable, and able to cover all scenarios.