How to mock self in python?
<p>Consider the following code. I want to mock <code>self.get_value</code>, which is invoked in <code>foo.verify_client()</code></p>

<pre><code>import unittest
import mock

def mock_get_value(self, value):
    return 'client'

class Foo:
    def __init__(self):
        pass
    def get_value(self, value):
        return value
    def verify_client(self):
        client = self.get_value('client')
        return client == 'client'

class testFoo(unittest.TestCase):
    @mock.patch('self.get_value', side_effect = mock_get_value, autospec = True)
    def test_verify_client(self):
        foo = Foo()
        result = foo.verify_client()
        self.assertTrue(result)

if __name__ == "__main__":
    unittest.main()
</code></pre>

<p>But I failed, the errors are as follows.</p>

<pre><code>E
======================================================================
ERROR: test_verify_client (__main__.testFoo)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/apps/Python/lib/python2.7/site-packages/mock/mock.py", line 1297, in patched
    arg = patching.__enter__()
  File "/apps/Python/lib/python2.7/site-packages/mock/mock.py", line 1353, in __enter__
    self.target = self.getter()
  File "/apps/Python/lib/python2.7/site-packages/mock/mock.py", line 1523, in &lt;lambda&gt;
    getter = lambda: _importer(target)
  File "/apps/Python/lib/python2.7/site-packages/mock/mock.py", line 1206, in _importer
    thing = __import__(import_path)
ImportError: No module named self

----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (errors=1)
</code></pre>

<p>How can I do it?</p>

<p>I figured it out. Changing this line</p>

<pre><code>@mock.patch('self.get_value', side_effect = mock_get_value, autospec = True)
</code></pre>

<p>to</p>

<pre><code>@mock.patch('test.Foo.get_value', mock_get_value)
</code></pre>

<p>worked.</p>

<p>Especially, the format of the patched function should be <code>module_name + class_name + method_name</code></p>

python unit-testing mocking