25

I'd like to replace a method in a class with mock:

from unittest.mock import patch

class A(object):
    def method(self, string):
        print(self, "method", string)

    def method2(self, string):
        print(self, "method2", string)

with patch.object(A, 'method', side_effect=method2):
    a = A()
    a.method("string")
    a.method.assert_called_with("string")

...but I get insulted by the computer:

TypeError: method2() missing 1 required positional argument: 'string'

1 Answer 1

32

The side_effect parameter indicates that a call to method should have a call to method2 as a side effect.

What you probably want is to replace method1 with method2, which you can do by using the new parameter:

with patch.object(A, 'method', new=method2):

Be aware that if you do this, you cannot use assert_called_with, as this is only available on actual Mock objects.

The alternative would be to do away with method2 altogether and just do

with patch.object(A, 'method'):

This will replace method with a Mock instance, which remembers all calls to it and allows you to do assert_called_with.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.