1

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)
Simen Russnes
  • 2,002
  • 2
  • 26
  • 56
  • Not exactly. At least I can't see how my `do_something` function would have access to the subclass. How would I inject it into the module? – Simen Russnes Jul 22 '20 at 13:48
  • Furthermore, I'd like to run the `assert_called_once` on the created object, and for that I would need to constructor to return a `Mock` that I can specify in the test. – Simen Russnes Jul 22 '20 at 13:54
  • You are right - this does not fit you. At a second glance, it looks like you are just mocking the wrong object. `@mock.patch('my_package.my_functions.MyClass')` should work better - see [where to patch](https://docs.python.org/3/library/unittest.mock.html#id6). This [answer](https://stackoverflow.com/a/62232014/12480730) I wrote recently is probably related. – MrBean Bremen Jul 22 '20 at 14:03

0 Answers0