如何模拟类属性?模拟的属性在类中不起作用。
代码示例:
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'
最佳答案
只需用属性修补它:
with mock.patch.object(Box, 'size', property(get_new_size)):
print(box.volume())
请注意,您还需要让 get_new_size
接受参数:
def get_new_size(self):
return 42
关于用于属性的 Python mock.patch.object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41276912/