Mocking an object retaining its functionality in Python
<p>I'm testing the behavior of an object. In the sample code below, I check if the method <code>bar2</code> is called.</p>

<p>The debug print shows that yes, <code>bar2</code> is called. Unfortunately, the <code>mock</code>-library doesn't track this call.</p>

<p>What should I do to make <code>mock</code> to notice such "internal" calls?</p>

<pre><code>import mock

class Foo:
  def bar1(self):
    print "in bar1"
    self.bar2()
  def bar2(self):
    print "in bar2"

m = mock.Mock(wraps = Foo())
m.bar1()
print "Method calls:", m.method_calls
m.bar2.assert_called_with()
</code></pre>

<p>Output:</p>

<pre><code>in bar1
in bar2
Method calls: [call.bar1()]
...
AssertionError: Expected call: bar2()
Not called
</code></pre>

<p><strong>Update</strong></p>

<p>I've accepted the answer with patching as the methodically correct, but would like also to show my direct approach:</p>

<pre><code>obj = Foo()
m = mock.Mock(wraps = obj)
obj.bar2 = m.bar2 # Patch the object manually

m.bar1()

m.bar2.assert_called_with()
</code></pre>

<p>You don't. You mocked out <code>Foo()</code>, so the implementation is gone; the whole point of mocking is to replace the class. </p>

<p>If you are testing <code>Foo</code> itself, don't mock the class. You can mock individual methods instead:</p>

<pre><code>with mock.patch('__main__.Foo.bar2') as bar2_mock:
    f = Foo()
    f.bar1()
    print "Method calls:", bar2_mock.method_calls
    bar2_mock.assert_called_with()
</code></pre>

<p>This outputs:</p>

<pre><code>in bar1
Method calls: []
</code></pre>

<p>as now only <code>bar2</code> has been mocked.</p>

python mocking