Unable to patch class instantiated by the tested class using unittest
<p>I am trying to patch a class that is instantiated by the class I am trying to test, but it doesn't work. I have read the various docs but still haven't found what I am doing wrong. Here is the code snippet:</p>

<p>In <code>tests/Test.py</code>:</p>

<pre><code>from module.ClassToTest import ClassToTest

class Test(object):

    @mock.patch('module.ClassToPatch.ClassToPatch', autospec = False)
    def setUp(self, my_class_mock):
        self.instance = my_class_mock.return_value
        self.instance.my_method.return_value = "def"
        self.class_to_test = ClassToTest()

    def test(self):
        val = self.class_to_test.instance.my_method() #Returns 'abc' instead of 'def'
        self.assertEqual(val, 'def')
</code></pre>

<p>In <code>module/ClassToPatch.py</code>:</p>

<pre><code>class ClassToPatch(object):
    def __init__(self):
        pass
    def my_method(self):
        return "abc"
</code></pre>

<p>In <code>module/ClassToTest.py</code>:</p>

<pre><code>from module.ClassToPatch import ClassToPatch

class ClassToTest(object):
    def __init__:
        # Still instantiates the concrete class instead of the mock
        self.instance = ClassToPatch()
</code></pre>

<p>I know in this case I could easily inject the dependency, but this is just an example. Also, we use a single class per file policy, with the file named like the class, hence the weird import naming.</p>