如何修补对象中的属性

时间:2014-01-12 11:30:58

标签: python unit-testing mocking

问题是如何在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'>

2 个答案:

答案 0 :(得分:18)

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}

答案 1 :(得分:0)

配置文件

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