0

有什么方法可以延迟模拟副作用的评估。

def mockfunc(wheel):
    wheel.rubber = soft

wheel.make = Mock(side_effect=mockfunc(wheel)))

这里的问题是我试图替换“wheel.make”方法,这样当它在测试中被调用时,mockfunc 被调用,并且设置了一个轮子属性而不是运行通常的方法。

事情是-当我设置side_effect时,mockfunc调用立即发生,橡胶属性设置为soft。在调用方法 wheel.make 之前,我不希望这种情况发生。

4

1 回答 1

0

根据side_effect文档,它应该是可调用的、可迭代的或异常(类或对象)。此外,我猜您想替换's Classmake中的 unboundmethod wheel:要进行此类修补,您应该使用patchpatch.object作为上下文或装饰器,如此所述。

以下是如何做到这一点的完整示例:

from mock import patch

class Wheel():
    def __init__(self):
        self.rubber = 0

    def make(self):
        self.rubber = 10

soft = 36
def mockfunc(wheel):
    wheel.rubber = soft

wheel = Wheel()
print("unpatched wheel before make rubber = {}".format(wheel.rubber))
wheel.make()
print("unpatched wheel after make rubber = {}".format(wheel.rubber))

with patch.object(Wheel, "make", side_effect=mockfunc, autospec=True):
    print("patched wheel before make rubber = {}".format(wheel.rubber))
    wheel.make()
    print("patched wheel after make rubber = {}".format(wheel.rubber))

输出是

unpatched wheel before make rubber = 0
unpatched wheel after make rubber = 10
patched wheel before make rubber = 10
patched wheel after make rubber = 36
于 2015-01-19T08:48:55.160 回答