相关疑难解决方法(0)

如何模拟财产

我问如何使用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)

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

python pytest python-3.x python-mock python-unittest

6
推荐指数
1
解决办法
5597
查看次数