Python unittest mock class and class method
I am not sure about the implementation of create_class_call_method
, but try the following:
from unittest import mock
class MyClassTestCase(unittest.TestCase):
@mock.patch('tmp.my_module.MyClass.my_method')
@mock.patch('tmp.my_module.MyClass.__init__')
def test_create_class_call_method(self, my_class_init, my_method_mock):
my_class_init.return_value = None
my_method.return_value = 2
value = my_module.create_class_call_method()
self.assertEqual(value, 2)
I've found a much better solution. In short, we need to mock out the return_value
of the MyClass
mock. Here's the working test code:
import unittest
from unittest.mock import patch, Mock, MagicMock
from tmp import my_module
class MyClassTestCase(unittest.TestCase):
def test_create_class_call_method(self):
# Create a mock to return for MyClass.
m = MagicMock()
# Patch my_method's return value.
m.my_method = Mock(return_value=2)
# Patch MyClass. Here, we could use autospec=True for more
# complex classes.
with patch('tmp.my_module.MyClass', return_value=m) as p:
value = my_module.create_class_call_method()
# Method should be called once.
p.assert_called_once()
# In the original my_method, we would get a return value of 1.
# However, if we successfully patched it, we'll get a return
# value of 2.
self.assertEqual(value, 2)
if __name__ == '__main__':
unittest.main()
And the successful results:
Ran 1 test in 0.002s
OK