How can I test the constructor of my class, and subsequent objects created by it? I tried different combinations, and patching the __init__
function of MyClass
, but I get different errors depending on what I try, for example __init__() should return None, not 'Mock'
.
How should I patch to make the below test pass?
test_mystuff.py
import unittest.mock as mock
import unittest
from unittest.mock import Mock
from my_package.my_functions import do_something
class MyTestCase(unittest.TestCase):
@mock.patch('my_package.my_classes.MyClass')
def test_object_is_created_and_does_action(self, mock_class):
arg1 = Mock()
arg2 = Mock()
mock_object = Mock()
mock_class.return_value = mock_object
do_something(arg1, arg2)
mock_class.assert_called_with(arg1, arg2)
mock_object.do_action.assert_called_once()
my_functions
from my_package.my_classes import MyClass
def do_something(arg1, arg2):
my_object = MyClass(arg1, arg2)
my_object.do_action()
my_classes.py
class MyClass(object):
def __init__(self, arg1, arg2):
self.arg1 = arg1
self.arg2 = arg2
def do_action(self):
print(self.arg1)