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
- Mock API calls in tests
- Patch datetime for time-dependent code
- Use side_effect for multiple return values
- Create mock for database connection
- Test error handling with mocks