Reusing Mock to create attribute mocks unittest.patch
<pre><code>from unittest.mock import patch


class A:
    def b(self):
        return 'HAHAHA A'
a = A()

with patch('__main__.A') as a_mock:
    a_mock.b.return_value = 'not working'
    print(a.b())

HAHAHA A
&gt;&gt;&gt;
</code></pre>

<p>Why doesn't it print <code>'not working'</code>? What for is a_mock, then? ______________</p>

<p>You replaced the <em>whole class</em> with your patch, not the method on the existing class. <code>a = A()</code> created an instance of <code>A</code> before you replaced the class, so <code>a.__class__</code> still references the actual class, not the mock.</p>

<p>Mocking can only ever replace one reference at a time, and not the object referenced. Before the patch, both the names <code>A</code> and the attribute <code>a.__class__</code> are references to the class object. You then patched only the <code>A</code> reference, leaving <code>a.__class__</code> in place.</p>

<p>In other words, <code>a.__class__</code> is not patched, only <code>A</code>, and <code>A().b()</code> <em>would</em> print <code>not working</code>.</p>

<p>You'd have to patch <em>just</em> the method on the class, so that <code>a.__class__</code> still references <code>A</code>, and  <code>a.b</code> will resolve to the patched <code>A.b</code> mock:</p>

<pre><code>with patch('__main__.A.b') as b_mock:
    b_mock.return_value = 'working as long as you patch the right object'
    print(a.b())
</code></pre>

<p>Demo:</p>

<pre><code>&gt;&gt;&gt; with patch('__main__.A.b') as b_mock:
...     b_mock.return_value = 'working as long as you patch the right object'
...     print(a.b())
...
working as long as you patch the right object
</code></pre>

<p>You can't, unfortunately, patch the <code>a.__class__</code> reference with a <code>Mock</code>; Python only lets you use actual classes for that attribute.</p>

<pre><code>&gt;&gt;&gt; with patch('__main__.a.__class__') as a_class_mock:
...     a_class_mock.b.return_value = 'working as long as you patch the right object'
...     print(a.b())
...
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
  File "/Users/mjpieters/Development/Library/buildout.python/parts/opt/lib/python3.5/unittest/mock.py", line 1312, in __enter__
    setattr(self.target, self.attribute, new_attr)
TypeError: __class__ must be set to a class, not 'MagicMock' object
</code></pre>

python mocking python-unittest