Mock Objects with unittest.mock
Mock objects replace real objects in your tests, allowing you to control their behavior
and verify interactions. The unittest.mock module provides powerful mocking
capabilities without external dependencies.
Creating a Mock
import unittest
from unittest.mock import Mock
class TestWithMock(unittest.TestCase):
def test_mock_method(self):
mock_service = Mock()
mock_service.get_user.return_value = {"name": "Alice"}
result = mock_service.get_user(1)
self.assertEqual(result["name"], "Alice")
mock_service.get_user.assert_called_once_with(1)
def test_mock_not_called(self):
mock_service = Mock()
# Don't call any methods
mock_service.get_user.assert_not_called()
Mocking External Services
from unittest.mock import Mock, patch
class TestPayment(unittest.TestCase):
def test_process_payment(self):
payment_gateway = Mock()
payment_gateway.charge.return_value = {"status": "success", "id": "txn_123"}
processor = PaymentProcessor(payment_gateway)
result = processor.process_payment(amount=50.00)
self.assertTrue(result.success)
payment_gateway.charge.assert_called_once_with(amount=50.00)
Mock Return Values
mock_obj = Mock()
# Single return value
mock_obj.method.return_value = 42
# Side effects (exceptions)
from unittest.mock import side_effect
mock_obj.method.side_effect = ConnectionError("Timeout")
# Side effects (multiple values)
mock_obj.method.side_effect = [1, 2, 3]
# Usage
print(mock_obj.method()) # 1
print(mock_obj.method()) # 2
print(mock_obj.method()) # 3
Key Takeaway
Mock objects let you replace dependencies with controllable fakes.
Use return_value to set what methods return, and side_effect
for exceptions or dynamic behavior.