问题是如何在with
语句中修补实例的属性。我试过用以下不起作用的例子。它打印在注释中。
from mock import patch, PropertyMock
class Foo(object):
f = {'a': 1}
new_foo = Foo()
with patch.object(new_foo, 'f', new_callable=PropertyMock) as mock:
mock.return_value = {'b': 2}
print new_foo.f
# <PropertyMock name='f' id='4474801232'>
最佳答案
documentation中有一个例子。您需要将类提供给patch.object,而不是实例化的对象。
from mock import patch, PropertyMock
class Foo(object):
f = {'a': 1}
new_foo = Foo()
with patch.object(Foo, 'f', new_callable=PropertyMock) as mock:
mock.return_value = {'b': 2}
print new_foo.f
print new_foo.f
输出:
{'b': 2}
{'a': 1}
关于python - 如何修补对象中的属性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21074090/