3

我试图让模拟库返回带有补丁的特定模拟对象。无论我尝试什么,如果我在我的“with”子句中实例化一个新对象,我会得到一个通用的 Mock 对象,而不是我自定义的对象。

这是我的代码,以日志记录为例:

    import logging

    my_mock = Mock()
    my_mock.id = 'i-12341234'

    with patch('logging.PlaceHolder', new=my_mock) as mockobj:
        print mockobj.id          # correctly prints 'i-12341234'

        newobj = logging.PlaceHolder(None)
        print newobj.id           # prints <Mock name='mock().id' id='47607184'>

每次实例化一个新的 logging.Placeholder 实例时,我如何才能获得模拟以返回 my_mock?

事实证明,子类化 Mock 并使用 new_callable 传递它。由于我花时间尝试使上述版本正常工作,我仍然会很感激并回答。

4

1 回答 1

0
import logging
from mock import Mock, patch

my_mock = Mock()
my_mock.id = 'i-12341234'

with patch('logging.PlaceHolder', new=my_mock) as mockobj:
    mockobj.return_value = mockobj # <-- added this line.
    print mockobj.id
    newobj = logging.PlaceHolder(None)
    print newobj.id

选择

import logging
from mock import Mock, patch

my_mock = Mock()
my_mock.id = 'i-12341234'
my_mock.return_value = my_mock # <---

with patch('logging.PlaceHolder', new=my_mock) as mockobj:
    assert mockobj.id == 'i-12341234'
    newobj = logging.PlaceHolder(None)
    assert newobj.id == 'i-12341234'
于 2013-06-27T14:18:33.117 回答