python - 测试函数内部的方法调用
问题描述
我需要模拟我在函数中调用其方法的对象。该对象在函数内部初始化,这就是问题所在。如何用模拟替换它的实现?
功能代码:
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()
正如预期的那样,这不起作用。该函数将在另一个模块中调用,我无法在那里传递模拟对象。有想法该怎么解决这个吗?
解决方案
您应该改为模拟课程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()
推荐阅读
- angular - NGXS @Action 方法未调用
- selenium - Macbook m1 上的硒
- java - 扫描仪中的分隔符,保留分隔符
- android - 从一台机器创建的项目复制到另一台机器时的 SDK 路径问题
- javascript - 未处理的拒绝(TypeError):无法读取 React.js 中 stripe.confirmCardPayment 中未定义的属性“id”
- javascript - 更改“-1”答案,当 indexof 未找到任何匹配项时
- html - 将鼠标悬停在响应式列图像上时如何显示文本?
- angularjs - $rootScope 存储在组件 $scope 中
- tensorflow - 使用用 coco 训练的图像分类模型
- r - ggplot如何显示上个月的数据