How to mock an imported instance method

I am writing a unit test for some python modules. However, I cannot work out a way to mock the imported instance method. Below are the python modules that I want to test.

- bar.py -

class A():
    @classmethod
    def method_1(self):
        ...    
a = A()

      

- foo.py -

from bar import a
class B():
    @classmethod
    def b(cls):
        if a.method_1():
            return True
        else:
            return False

      

- test_foo.py -

from foo import B

class TestB(TestCase):
    @patch('foo.a.method_1')
    def test_b(self, mock_method_1):
          mock_method_1.return_value = True
          test_b = B.b()
          ...

      

This does not work. My test case is still calling the original one method_1

instead of the one I mocked.

+3


source to share


1 answer


Use patch.object

decorator
instead . It fixes the attributes of the objects, it does not fix the global method.

If that doesn't work, try fixing bar.a

instead foo.a

, but I don't think your problem is here.

Update



The question changed to a class method, so I think this will work:

- test_foo.py -

from foo import B

class TestB(TestCase):
    @patch('bar.A.method_1')
    def test_b(self, mock_method_1):
          mock_method_1.return_value = True
          test_b = B.b()
          ...

      

0


source







All Articles