Python mock.patch.object属性

时间:2016-12-22 06:22:16

标签: python unit-testing mocking

如何模拟类属性?被嘲笑的财产在课堂上不起作用。

代码示例:

class Box(object):
    def __init__(self, size):
        self._size = size

    @property
    def size(self):
        return self._size

    def volume(self):
        print(self.size)
        return self.size**3

def get_new_size():
    return 42


box = Box(13)
with mock.patch.object(Box, 'size', get_new_size):
    print(box.volume())

返回:

<bound method Box.get_new_size of <__main__.Box object at 0x10a8b2cd0>>
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "<stdin>", line 9, in volume
TypeError: unsupported operand type(s) for ** or pow(): 'instancemethod' and 'int'

1 个答案:

答案 0 :(得分:2)

只需使用属性修补它:

with mock.patch.object(Box, 'size', property(get_new_size)):
    print(box.volume())

请注意,您还需要使get_new_size接受参数:

def get_new_size(self):
    return 42