首页 > 解决方案 > 测试函数内部的方法调用

问题描述

我需要模拟我在函数中调用其方法的对象。该对象在函数内部初始化,这就是问题所在。如何用模拟替换它的实现?

功能代码:

def handler (event, context):
    """Function, when call Yandex Server less"""
    function_heandler = Handler(event=event, context=context)
    response = function_heandler.run()
    return response

测试代码:

def test_main_call_handler():
    with mock.patch('function.handler.Handler', new=mock.MagicMock()) as mock_handler:
        handler({}, object())
        mock_handler.run.assert_called()

正如预期的那样,这不起作用。该函数将在另一个模块中调用,我无法在那里传递模拟对象。有想法该怎么解决这个吗?

标签: pythonmockingpytest

解决方案


您应该改为模拟课程Handler

假设Handler从 导入package.module,您可以简单地修补package.module.Handler

def test_main_call_handler():
    with mock.patch('package.module.Handler') as mock_handler:
        handler({}, object())
        mock_handler.run.assert_called()

推荐阅读