Bird
Raised Fist0
PythonHow-ToBeginner · 3 min read

How to Mock Function in Python Test: Simple Guide

To mock a function in a Python test, use the unittest.mock.patch decorator or context manager to replace the target function with a mock object. This lets you control its behavior and check how it was called without running the real function.
📐

Syntax

The unittest.mock.patch is used to replace a function during a test. It can be applied as a decorator or used with a with statement.

  • @patch('module.function'): Replaces function in module with a mock for the test.
  • with patch('module.function') as mock_func:: Temporarily mocks the function inside the block.
  • The mock object can be configured to return values or check calls.
python
from unittest.mock import patch

@patch('math.sqrt')
def test_sqrt(mock_sqrt):
    mock_sqrt.return_value = 3
    result = mock_sqrt(9)
    assert result == 3
    mock_sqrt.assert_called_once_with(9)
💻

Example

This example shows how to mock a function get_data from a module data_source. The test replaces get_data with a mock that returns a fixed value, so the test does not depend on real data.

python
from unittest.mock import patch

def get_data():
    # Imagine this fetches data from the internet
    return {'value': 42}

def process_data():
    data = get_data()
    return data['value'] * 2

@patch('__main__.get_data')
def test_process_data(mock_get_data):
    mock_get_data.return_value = {'value': 10}
    result = process_data()
    print(result)  # Should print 20

if __name__ == '__main__':
    test_process_data()
Output
20
⚠️

Common Pitfalls

Common mistakes when mocking functions include:

  • Mocking the wrong import path. You must patch where the function is used, not where it is defined.
  • Not setting return_value or side effects, so the mock returns MagicMock objects unexpectedly.
  • Forgetting to assert calls to verify the mock was used as expected.
python
from unittest.mock import patch

def external_func():
    return 5

def caller():
    return external_func()

# Correct patch: patch where caller uses it
@patch('__main__.external_func')
def test_correct_patch(mock_func):
    mock_func.return_value = 20
    result = caller()
    print(result)  # Prints 20

if __name__ == '__main__':
    test_correct_patch()
Output
20
📊

Quick Reference

ActionUsage ExampleDescription
Mock a function@patch('module.func')Replace func with a mock during test
Set return valuemock_func.return_value = 5Make mock return 5 when called
Assert callmock_func.assert_called_once_with(args)Check mock was called with args
Use as context managerwith patch('module.func') as mock_func:Mock only inside this block
✅

Key Takeaways

Use unittest.mock.patch to replace functions with mocks in tests.
Always patch the function where it is used, not where it is defined.
Set return_value on mocks to control their output.
Assert mock calls to verify your code interacts correctly.
Use patch as a decorator or context manager for flexible mocking.