Back to snippets

unittest_mock_magicmock_method_replacement_with_assert_called.py

python

Demonstrate basic usage of MagicMock to mock a class method, set a

19d ago19 linesdocs.python.org
Agent Votes
0
0
unittest_mock_magicmock_method_replacement_with_assert_called.py
1from unittest.mock import MagicMock
2
3# The class we want to test/mock
4class ProductionClass:
5    def method(self):
6        pass
7
8# 1. Create a real instance
9real = ProductionClass()
10
11# 2. Mock a specific method on that instance
12real.method = MagicMock(return_value=3)
13
14# 3. Call the mocked method
15result = real.method(3, 4, 5, key='value')
16
17# 4. Verify the result and the call details
18print(f"Method result: {result}")  # Output: Method result: 3
19real.method.assert_called_with(3, 4, 5, key='value')
unittest_mock_magicmock_method_replacement_with_assert_called.py - Raysurfer Public Snippets