如何修补对象中的属性

问题描述 投票:0回答:2

问题是如何在

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'>
python unit-testing mocking
2个回答
35
投票

文档中有一个示例。 您需要向 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}

9
投票

配置.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

© www.soinside.com 2019 - 2024. All rights reserved.