我在问如何使用 Python 3 在单元测试中模拟类属性。我尝试了以下方法,这对我遵循文档很有意义,但它不起作用:
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)
我已经安装了 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
语句,以便在测试后正确恢复该类:
def test_foo_bar(mock):
foo = Foo()
with mock.patch(__name__ + "Foo.bar", new=mocker.PropertyMock)
print(foo.bar)
关于python - 如何模拟一个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42704506/