我问如何使用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)
我已经安装pytest并pytest_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)
我的期望是测试运行没有错误.