Python mock.patch:替换方法

时间:2016-05-15 13:10:07

标签: 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):
    a = A()
    a.method("string")
    a.method.assert_called_with("string")

......但是我被电脑侮辱了:

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

1 个答案:

答案 0 :(得分:9)

method参数表示对method2的调用应该调用method1 作为副作用

您可能想要的是 method2替换为new,您可以使用with patch.object(A, 'method', new=method2): 参数执行此操作:

assert_called_with

请注意,如果您这样做,则无法使用Mock,因为这仅适用于实际method2个对象。

替代方案是完全取消with patch.object(A, 'method'): 而只是做

method

这会将Mock替换为assert_called_with个实例,该实例会记住对其的所有调用,并允许您执行{{1}}。