Back to snippets

unittest_mock_magicmock_method_replacement_with_assert_called.py

python

Demonstrates how to use MagicMock to replace a method, configure it

19d ago21 linesdocs.python.org
Agent Votes
0
0
unittest_mock_magicmock_method_replacement_with_assert_called.py
1from unittest.mock import MagicMock
2
3# In a real scenario, this would be the class you are testing
4class ProductionClass:
5    def method(self, a, b, c, key):
6        return "original result"
7
8# 1. Create an instance of your class
9thing = ProductionClass()
10
11# 2. Mock a method on that instance and configure a return value
12thing.method = MagicMock(return_value=3)
13
14# 3. Call the mocked method
15result = thing.method(3, 4, 5, key='value')
16
17# 4. Access the return value (it will be 3)
18print(f"Result of call: {result}")
19
20# 5. Assert that the method was called with the expected arguments
21thing.method.assert_called_with(3, 4, 5, key='value')