I have a python file a.py which contains two classes A and B.
class A(object):
def method_a(self):
return "Class A method a"
class B(object):
def method_b(self):
a = A()
print a.method_a()
I would like to unittest method_b in class B by mocking A. Here is the content of the file testa.py for this purpose:
import unittest
import mock
import a
class TestB(unittest.TestCase):
@mock.patch('a.A')
def test_method_b(self, mock_a):
mock_a.method_a.return_value = 'Mocked A'
b = a.B()
b.method_b()
if __name__ == '__main__':
unittest.main()
I expect to get Mocked A in the output. But what I get is:
<MagicMock name='A().method_a()' id='4326621392'>
Where am I doing wrong?
A()returns thereturn_valuefrommock_A(a regularMagicMock, as you haven't specified anything else), which is not an instance of the classA. You need to set thatreturn_valueto be something that has a definedmethod_a.mock_athat should have the method, notmock_aitself.mock_a().method_a.return_value = 'Mocked A'andmock_a.return_value.method_a.return_value = 'Mocked A'worked. Thanks a lot for your comments. Would you please go ahead and put it as an answer?