1

I am new to unit testing in Python. I trying to write unit tests for my class. However I am running into issues:

from <path1> import InnerObj
from <path2> import new_obj
from <path3> import XYZ

class ClassToBeTested(object):

def __init__(self):
    obj = new_obj(param1 = "XYZ", time = 1, innerObj = InnerObj())
    self.attr1 = XYZ(obj)


 def method(self, random, paramStr):

 // Remainder of class

Test class:

from mock import patch, PropertyMock, MagicMock
from <path1> import InnerObj
from <path2> import new_obj
from <path3> import XYZ


@pytest.fixture()
@patch('<path1>.InnerObj', new=MagicMock())
@patch('<path2>.new_obj', new=MagicMock())
@patch('<path3>.XYZ', new=MagicMock())
def mock_test():
    return ClassToBeTested()

def test_method_true(mock_test):
     random = Random_Object()

     booleanResult = mock_test.method(random, paramStr)
     assert booleanResult == True

The error I get is ERROR at setup of test_method_true ______

The error stack mentions innerObj/init.py:26: in init qwerty_main = qwerty_assistant.get_root()

I am likely to believe that mocking is not done correctly for InnerObj as it should not be invoking the code in the init method of mocked objects.

Am I doing something wrong here? Can someone please help in pointing to right direction?

Thanks

1 Answer 1

1

patch should target the import that is being used and not the path to the import.

For example

@patch('<path1>.InnerObj', new=MagicMock())

<path1> is the location to the definition of InnerObj and not the file using it. To address this, the InnerObj import should be patched in the module that imports InnerObj

Pretend that the path to ClassToBeTested is path.to.class.to.be.tested

The patch would be:

@patch('path.to.class.to.be.tested.InnerObj', new=MagicMock())

Sign up to request clarification or add additional context in comments.

2 Comments

I believe thats what I am doing. value of <path1> is the same that is used in the import statements in the test class as well as original code. The same value of <path1> is patched as well
It should NOT be the path used in the import statement , it should be the path to the class which is importing it, in this case the file that contains Classtobetested

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.