如何模拟财产

hek*_*mgl 6 python pytest python-3.x python-mock python-unittest

我问如何使用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)
Run Code Online (Sandbox Code Playgroud)

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

pytest foo.py
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

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

/usr/lib/python3.5/unittest/mock.py:1312: AttributeError
Run Code Online (Sandbox Code Playgroud)

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

jsb*_*eno 9

属性机制依赖于依赖于在对象类上定义的属性属性.您不能在类的单个实例上创建"类似属性"的方法或属性(为了更好地理解,请阅读Python的描述符协议)

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

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