在创建的对象上调用测试方法

时间:2018-03-19 17:11:50

标签: python magicmock

我是Python新手,请原谅我,如果这是基本的话。我有一个正在测试的方法,在该方法中,我实例化一个对象并在其上调用方法,并想测试那些被正确调用(值得指出这个代码是预先存在的,我只是添加它,与没有现有的测试。)

正在测试的方法

def dispatch_events(event):
    dispatcher = Dispatcher()
    dispatcher.register("TopicOne")
    dispatcher.push(event)

预期测试

# Some patch here
def test_dispatch_events(self, mock_dispatcher):
    # Given
    event = { "some_prop": "some_value" }

    # When
    Class.dispatch_events(event)

    # Then
    mock_dispatcher.register.assert_called_once_with("TopicOne")
    mock_dispatcher.push.assert_called_once_with(event)

来自.NET背景我立即想到将Dispatcher作为参数传递给dispatch_events。然后据推测,我可以传入MagicMock版本。或者我认为您可以在__init__上修补Dispatcher方法并返回MagicMock。在继续这之前,我想知道a)是否可能和b)测试这个的最佳实践是什么(完全接受编写更好的方法可能是最佳实践)。

1 个答案:

答案 0 :(得分:1)

dispatcher成为一个参数,你不需要修补任何东西。

def dispatch_events(event, dispatcher=None):
    if dispatcher is None:
        dispatcher = Dispatcher()
    dispatcher.register("TopicOne")
    dispatcher.push(event)

def test_dispatch_events(self):
    event = {"some_prop": "some_value"}
    mock_dispatcher = Mock()
    Class.dispatch_events(event, mock_dispatcher)
    mock_dispatcher.register.assert_called_once_with("TopicOne")
    mock_dispatcher.push.assert_called_once_with(event)

如果这不是一个选项,那么在大多数情况下模拟的正确方法是Dispatcher.__new__some.module.Dispatcher本身。

# The exact value of 'some.module' depends on how the module that
# defines dispatch_events gets access to Dispatcher.
@mock.patch('some.module.Dispatcher')
def test_dispatch_events(self, mock_dispatcher):
    event = {"some_prop": "some_value"}
    Class.dispatch_events(event)
    mock_dispatcher.register.assert_called_once_with("TopicOne")
    mock_dispatcher.push.assert_called_once_with(event)