简体   繁体   中英

Python mock.patch: replace a method

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'

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM