javex
javex

Reputation: 7544

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?

Upvotes: 5

Views: 8045

Answers (1)

and
and

Reputation: 2092

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)

Upvotes: 11

Related Questions