用于属性的 Python mock.patch.object

标签 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'

最佳答案

只需用属性修补它:

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/

相关文章:

python - 正则表达式不匹配

Python Excel COM 互操作 : Force headless mode and prevent user inputs

visual-studio-2008 - 使用访问器进行单元测试

Python:如何模拟 datetime.utcnow()?

c# - 如何用最小起订量模拟 System.Xml.XmlWriter.WriteAttributeString()?

python - 使用另一个 numpy 数组元素作为索引向量化更新 numpy 数组

python - Docker权限错误: [Errno 13] Permission denied: 'tmp'

c# - 为单元测试设置类的只读属性

unit-testing - 如何在不同的包中测试未导出的结构字段?

XDocument.Load() 和 XDocument.Save() 的测试方法