Python mock.patch:替换方法

Python mock.patch:替换方法,python,mocking,Python,Mocking,我想用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):

我想用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")
…但我被电脑侮辱了:

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

side_effect
参数表示调用
method
应该调用
method2
作为副作用

您可能需要将
method1
替换为
method2
,您可以使用
new
参数:

与patch.object(一个'method',new=method2):
请注意,如果执行此操作,则不能将名为_的
assert_与
一起使用,因为这仅适用于实际的
Mock
对象

另一种选择是完全废除
method2
,只需这样做

带有patch.object(一个“方法”)的
这将用一个
Mock
实例替换
method
,该实例将记住对它的所有调用,并允许您使用
执行
assert\u调用