我在问如何使用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)
我已经安装了pytest
和pytest_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
我的期望是测试运行时没有错误。
属性机制依赖于在对象的类上定义的属性属性。不能在类的单个实例上创建“类似属性”的方法或属性(为了更好地理解,请阅读Python的descriptor protocol)
因此,您必须将修补程序应用于您的类-您可以使用
with
语句,以便在测试后正确还原该类:相关问题 更多 >
编程相关推荐