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

Testing methods are called on object created

我是 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版本。或者我认为您可以在 Dispatcher 和 return 和 MagicMock 上修补 __init__ 方法。在继续之前,我想知道 a) 是否可行以及 b) 测试它的最佳实践是什么(完全接受编写更好的方法可能是最佳实践)。

使 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)