Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock a base class's method when it was overridden?

I have a code similar to this:

from mock import MagicMock


class Parent(object):

    def test_method(self, param):
        # do something with param
        pass


class Child(Parent):

    def test_method(self, param):
        # do something Child-specific with param
        super(Child, self).test_method(param)

Now I want to make sure that Child.test_method calls Parent.test_method. For this, I'd like to use assert_called_once_with from the mock module/library. However, I cannot figure out a way to do this. If the method would not be overridden by the subclass this would be easy as pointed out by Need to mock out some base class behavior in a python test case. However, in my case this is the same method, so what do I do?

like image 224
javex Avatar asked Jan 10 '23 23:01

javex


1 Answers

You can use patch.object:

with mock.patch.object(Parent, 'test_method') as mock_method:
    child = Child()
    mock_param = mock.Mock()
    child.test_method(mock_param)
    mock_method.assert_called_with(mock_param)
like image 151
and Avatar answered Jan 19 '23 15:01

and