← Back to Python

All Topics

Advertisement

Learn/Python/Advanced Python

Mocking and Patching

Topic: Testing

Advertisement

Introduction

Mocking replaces real objects with fake implementations for isolated testing.

Basic Mocking

from unittest.mock import Mock, MagicMock

# Create mock
mock_obj = Mock()
mock_obj.method.return_value = "value"

# Call mock
print(mock_obj.method())  # "value"
mock_obj.method.assert_called_once()

Patching

from unittest.mock import patch

# Patch a function
@patch("os.path.exists")
def test_file_processing(mock_exists):
    mock_exists.return_value = True
    result = process_file("test.txt")
    assert result is not None

# Context manager style
with patch("os.path.exists", return_value=True):
    result = process_file("test.txt")

Spy

from unittest.mock import patch

# Spy on real method
with patch.object(RealClass, "method", wraps=RealClass.method):
    obj = RealClass()
    obj.method()
    RealClass.method.assert_called()

Practice Problems

  1. Mock API calls in tests
  2. Patch datetime for time-dependent code
  3. Use side_effect for multiple return values
  4. Create mock for database connection
  5. Test error handling with mocks

Advertisement

Advertisement

Need More Practice?

Get personalized Python help from ChatWhole's AI-powered platform.

Get Expert Help →