Python mock.patch:替换方法
我想用mock替换类中的方法: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):
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调用