Mocking and Patching

Advanced PythonTestingFree Lesson

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

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement