0

我是 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) 测试它的最佳实践是什么(完全接受编写更好的方法可能是最佳实践)。

4

1 回答 1

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__orsome.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)
于 2018-03-19T17:31:46.750 回答