title: Mock a class in Python in order to call one of its methods
body: <p>I'm starting to learn Python, and along with that, I try learn how to write tests for my code. I've decided to use <strong>py.test</strong> and <strong>mock</strong> for that. I'm given a quite big and complex class, to write tests for, so for a start I decided to work on a simpler example of my own.</p>
  
  <p>So, I've written a very simple class (<code>person.py</code> in a package called <code>src_pkg</code>)</p>
  
  <pre><code>class Person():
  
  
      def __init__(self, name, age):
          self.name = name
          self.age = age
  
      def can_do_it(self, x):
          result = True if x &gt; 5 else False
          print "result: ", result
          return result
  </code></pre>
  
  <p>What I want to do, is mock the Person class, and create an instance of the mocked class, in order to be able to call the <code>can_do_it()</code> method. </p>
  
  <p>The reason I want to do that, is because the real class I'm working on, has a really complex constructor, and I don't want to make an instance of the class by writing something like <code>foo = Foo(x, y, z)</code></p>
  
  <p>So, I've written my test code (<code>test_person.py</code> in a package called <code>test_pkg</code>), which is the following:</p>
  
  <pre><code>from mock import patch
  
  class TestPerson():
  
      def test_can_do_it(self):
          with patch('src_pck.person.Person') as Person:
              person = Person.return_value
              print "can he do it? :", person.can_do_it(4)
  </code></pre>
  
  <p>but when I run:</p>
  
  <pre><code>$ py.test -v -s test_person.py
  </code></pre>
  
  <p>I get the following result:</p>
  
  <pre><code>platform linux2 -- Python 2.7.5 -- py-1.4.20 -- pytest-2.5.2 -- /home/kostas/.virtualenvs/excite/bin/python
  collected 1 items 
  
  test_person.py:5: TestPerson.test_can_do_it Can he do it? : &lt;MagicMock name='Person().can_do_it()' id='37709904'&gt;
  PASSED
  </code></pre>
  
  <p>I would expect that the expression <code>print "can he do it? :", person.can_do_it(4)</code> would result to <code>can he do it? : False</code>. As a result, there is no point of asserting anything.</p>
  
  <p>I think that when I run the test, it does not call the <code>can_do_it()</code> method at all! (otherwise the print statement of the method would be printed, right?)</p>
  
  <p>So, what am I doing wrong?</p>
  
  <p>Any help would be really appreciated.</p>
  
  <p>Thank you in advance.</p>