0
0
PyTesttesting~15 mins

Mock return values and side effects in PyTest - Build an Automation Script

Choose your learning style9 modes available
Mock a function to test return values and side effects
Preconditions (2)
Step 1: Create a mock for the external service function
Step 2: Set the mock to return a specific value when called
Step 3: Call the main function that uses the external service
Step 4: Verify the main function returns the mocked value
Step 5: Set the mock to raise an exception as a side effect
Step 6: Call the main function again and verify it handles the exception
✅ Expected Result: The test passes verifying the function returns the mocked value and correctly handles the side effect exception
Automation Requirements - pytest with unittest.mock
Assertions Needed:
Assert the function returns the mocked return value
Assert the function handles the side effect exception properly
Best Practices:
Use patch decorator or context manager to mock dependencies
Set return_value and side_effect on mocks explicitly
Keep tests isolated and independent
Use clear and descriptive assertion messages
Automated Solution
PyTest
from unittest.mock import patch
import pytest

# Example external service function to be mocked
def external_service():
    # Imagine this calls a real external API
    return "real data"

# Function under test that uses the external service
def process_data():
    try:
        data = external_service()
        return f"Processed {data}"
    except Exception:
        return "Error handled"

@patch('__main__.external_service')
def test_process_data(mock_service):
    # Mock return value
    mock_service.return_value = "mocked data"
    result = process_data()
    assert result == "Processed mocked data", f"Expected 'Processed mocked data' but got {result}"

    # Mock side effect to raise exception
    mock_service.side_effect = Exception("Service failure")
    result = process_data()
    assert result == "Error handled", f"Expected 'Error handled' but got {result}"

This test uses patch to replace external_service with a mock.

First, it sets return_value to simulate a successful call returning "mocked data". The test calls process_data and asserts the returned string includes the mocked data.

Next, it sets side_effect to raise an exception to simulate a failure. The test calls process_data again and asserts it returns the error handling message.

This approach isolates the function from the real external service, allowing controlled testing of different scenarios.

Common Mistakes - 3 Pitfalls
Not using patch to mock the external function
Setting return_value but forgetting to reset side_effect
{'mistake': 'Asserting on the mock instead of the function output', 'why_bad': 'Tests do not verify actual function behavior, only mock calls', 'correct_approach': "Assert on the function's return value or side effects, not just mock calls"}
Bonus Challenge

Now add data-driven testing with 3 different mocked return values and verify the function output for each

Show Hint