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