0
0
PyTesttesting~15 mins

Why mocking isolates code under test in PyTest - Automation Benefits in Action

Choose your learning style9 modes available
Test function behavior with mocked dependency
Preconditions (2)
Step 1: Create a test function that mocks the external dependency
Step 2: Call the function under test with the mock in place
Step 3: Verify the function returns expected result based on the mock
Step 4: Ensure the external dependency is not actually called
✅ Expected Result: The function under test returns the expected result using the mock, and no real external calls happen
Automation Requirements - pytest with unittest.mock
Assertions Needed:
Assert the function output matches expected value
Assert the mocked dependency was called as expected
Best Practices:
Use patch decorator or context manager to mock dependencies
Keep tests independent and isolated
Avoid calling real external services in tests
Automated Solution
PyTest
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.

Common Mistakes - 3 Pitfalls
Not using patch to mock external dependencies
Mocking the wrong import path
Not asserting that the mock was called
Bonus Challenge

Now add data-driven testing with 3 different mock return values and expected outputs

Show Hint