gully gully - 2 months ago 11
Python Question

Unable to mock class methods using unitest in python

module

a.ClassA
:

class ClassA():
def __init__(self,callingString):
print callingString

def functionInClassA(self,val):
return val


module
b.ClassB
:

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)


Python
unittest
class

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")


Assertion fails. Where exactly am I going wrong?
I am using python 2.7

Answer

You assigned to return_value twice:

classAmock.return_value=dummyMock
classAmock.return_value=Mock()

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

You don't need to create new mock objects; just use the default return_value attribute value:

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")

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

Comments