问题是如何在
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'>
文档中有一个示例。 您需要向 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}
配置.py
class myClass(object):
def __init(self):
self.greeting = "hola"
test_first_test.py
from config import myClass
@patch.object(myClass, "greeting", "what up homie")
def test_one(self):
print (myClass.greeting)
输出:
what up homie