How to mock function on a class instance ?
- User
How to mock function on a class instance ?
Assistant
In Python, you can mock a function on a specific class instance using the
unittest.mockmodule. Here's an example:import unittest import unittest.mock as mock class MyClass: def __init__(self): self.some_list = [1, 2, 3] def my_method(self): result = 0 for item in self.some_list: result += item return result class TestMyClass(unittest.TestCase): def setUp(self): self.my_class = MyClass() def test_my_method(self): # Mock the `my_list` attribute of `self.my_class` mock_list = [4, 5, 6] with mock.patch.object(self.my_class, 'some_list') as mock_list: # Call the `my_method` with the mocked attribute result = self.my_class.my_method() # Verify that the mocked attribute was called mock_list.assert_called_once() # Check the result of the `my_method` self.assertEqual(result, 21)
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.