如何模拟 属性

How to mock a property

我在问如何使用 Python 在单元测试中模拟 class 属性 3. 我尝试了以下方法,这对我遵循文档很有意义, 但它不起作用:

foo.py:

class Foo():
    @property
    def bar(self):
        return 'foobar'


def test_foo_bar(mocker):
    foo = Foo()
    mocker.patch.object(foo, 'bar', new_callable=mocker.PropertyMock)
    print(foo.bar)

我已经安装了 pytestpytest_mock 以及 运行 这样的测试:

pytest foo.py

我收到以下错误:

>       setattr(self.target, self.attribute, new_attr)
E       AttributeError: can't set attribute

/usr/lib/python3.5/unittest/mock.py:1312: AttributeError

我的期望是测试 运行 没有错误。

属性 机制依赖于在对象的 class 上定义的 属性 属性。您不能在 class 的单个实例上创建 "property like" 方法或属性(为了更好地理解,请阅读 Python 的 descriptor protocol

因此您必须将补丁应用到您的 class - 您可以使用 with 语句以便 class 在测试后正确恢复:

def test_foo_bar(mock):
    foo = Foo()
    with mock.patch(__name__ + "Foo.bar", new=mocker.PropertyMock)
        print(foo.bar)