如何模拟属性 [英] How to mock a property

查看:28
本文介绍了如何模拟属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

推荐答案

属性机制依赖于在对象类上定义的属性属性。不能在类的单个实例上创建"Property Like"方法或属性(要更好地理解,请阅读有关Python的descriptor protocol)

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

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

这篇关于如何模拟属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆