Python Unit Testing Mock incorrectly
<p>I am new to unit testing in Python. I trying to write unit tests for my class. However I am running into issues:</p>

<pre><code>from &lt;path1&gt; import InnerObj
from &lt;path2&gt; import new_obj
from &lt;path3&gt; 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
</code></pre>

<p>Test class:</p>

<pre><code>from mock import patch, PropertyMock, MagicMock
from &lt;path1&gt; import InnerObj
from &lt;path2&gt; import new_obj
from &lt;path3&gt; import XYZ


@pytest.fixture()
@patch('&lt;path1&gt;.InnerObj', new=MagicMock())
@patch('&lt;path2&gt;.new_obj', new=MagicMock())
@patch('&lt;path3&gt;.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
</code></pre>

<p>The error I get is <code>ERROR at setup of test_method_true ______</code></p>

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

<p>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. </p>

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

<p>Thanks</p>

<p><code>patch</code> should target the import that is being used and not the path to the import.</p>

<p>For example </p>

<p><code>@patch('&lt;path1&gt;.InnerObj', new=MagicMock())</code></p>

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

<p>Pretend that the path to <code>ClassToBeTested</code> is <code>path.to.class.to.be.tested</code></p>

<p>The patch would be:</p>

<p><code>@patch('path.to.class.to.be.tested.InnerObj', new=MagicMock())</code></p>

python unit-testing mocking