如何模拟属性

2024-05-17 02:35:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我在问如何使用Python3模拟单元测试中的类属性。我试过以下方法,这对我跟踪文档是有意义的,但它不起作用:

食物比:

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

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


Tags: pyselfnewfoopytestdef错误bar
1条回答
网友
1楼 · 发布于 2024-05-17 02:35:07

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

因此,您必须将修补程序应用于您的类-您可以使用with语句,以便在测试后正确还原该类:

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

相关问题 更多 >