You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python单元测试中Mock函数未生效,仍调用原函数致测试失败

问题分析与解决

你遇到的mock函数未生效问题,核心原因是导入方式和mock路径不匹配:

测试文件里用from notification import get_notification直接把函数导入到了当前测试模块的命名空间中,后续mock的是原模块notification里的函数,但实际调用的是测试模块里已经导入的函数引用,导致mock没起作用。

解决方法一:mock测试模块内的函数引用

修改测试用例,将mock路径指向当前测试模块里的get_notification:

from notification import get_notification
import pytest

def test_get_notifications(mocker):
    # mock当前测试模块内的get_notification引用
    mocker.patch(__name__ + '.get_notification', return_value="SUCCESS")
    # 提前定义some_data,避免未定义报错
    some_data = "test_content"
    result = get_notification(some_data)
    assert result == "SUCCESS"

解决方法二:通过模块调用函数,mock原模块路径

调整导入方式,导入整个模块,调用函数时通过模块访问,此时mock原模块的函数即可生效:

import notification
import pytest
from unittest.mock import patch

@patch.object(notification, 'get_notification')
def test_get_notifications(get_notification_mock):
    get_notification_mock.return_value = "SUCCESS"
    some_data = "test_content"
    # 通过模块访问函数,确保走mock后的逻辑
    result = notification.get_notification(some_data)
    assert result == "SUCCESS"

注:测试用例里的some_data需要提前定义,否则运行时会触发未定义报错。

内容的提问来源于stack exchange,提问作者hootowl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 04:42:38