Unable to mock class methods using unitest in python
<p>module <code>a.ClassA</code>:</p>

<pre><code>class ClassA():
    def __init__(self,callingString):
        print callingString

    def functionInClassA(self,val):
        return val
</code></pre>

<p>module <code>b.ClassB</code>:</p>

<pre><code>from a.ClassA import ClassA

class ClassB():
    def __init__(self,val):
        self.value=val

    def functionInsideClassB(self):
        obj=ClassA("Calling From Class B")
        value=obj.functionInClassA(self.value)
</code></pre>

<p>Python <code>unittest</code> class</p>

<pre><code>import unittest
from b.ClassB import ClassB
from mock import patch, Mock, PropertyMock,mock

class Test(unittest.TestCase):
    @patch('b.ClassB.ClassA',autospec = True)
    def _test_sample(self,classAmock):
        dummyMock=Mock()
        dummyMock.functionInClassA.return_value="mocking functionInClassA"
        classAmock.return_value=dummyMock

        obj=ClassB("dummy_val")
        obj.functionInsideClassB()

        assert dummyMock.functionInClassA.assert_called_once_with("dummy_val")
</code></pre>

<p>Assertion fails. Where exactly am I going wrong?
I am using python 2.7</p>

<p>You assigned to <code>return_value</code> twice:</p>

<pre><code>classAmock.return_value=dummyMock
classAmock.return_value=Mock()
</code></pre>

<p>That second assignment undoes your work setting up <code>dummyMock</code> entirely; the new <code>Mock</code> instance has no <code>functionInClassA</code> attribute set up.</p>

<p>You don't need to create new mock objects; just use the default <code>return_value</code> attribute value:</p>

<pre><code>class Test(unittest.TestCase):
    @patch('b.ClassB.ClassA', autospec=True)
    def test_sample(self, classAmock):
        instance = classAmock.return_value
        instance.functionInClassA.return_value = "mocking functionInClassA"

        obj = ClassB("dummy_val")
        obj.functionInsideClassB()

        instance.functionInClassA.assert_called_once_with("dummy_val")
</code></pre>

<p>You do <strong>not</strong> need to assert the return value of <code>assert_called_once_with()</code> as that is always <code>None</code> (making your extra <code>assert</code> fail, always). Leave the assertion to the <code>assert_called_once_with()</code> method, it'll raise as needed.</p>

python mocking python-unittest