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

单元测试:断言自定义异常处理函数被调用的实现问题

解决unittest中patch异常处理函数断言失败的问题

我之前也碰到过一模一样的坑!你现在的问题核心是patch的目标路径错了,Python的导入机制导致你mock的不是the_function实际调用的那个函数引用。

问题根源

当the_function所在的模块(比如叫test_target.py)执行from exception_handler_resides_here import exception_handler时,Python会把exception_handler函数的引用复制到test_target模块的命名空间里。而the_function调用的是自己模块里的这个引用,不是原模块exception_handler_resides_here里的函数。你之前patch的是原模块的函数,自然捕获不到调用。

解决方案:修正patch的路径

你需要patch的是the_function所在模块里的exception_handler引用,而不是原模块的。举个具体的例子:

假设你的项目结构是这样:

project/
├── exception_handler_resides_here.py  # 定义exception_handler
├── test_target.py                     # 定义the_function
└── test_case.py                       # 测试文件

1. 先看test_target.py的代码(确保导入方式)

from exception_handler_resides_here import exception_handler

def the_function(sth):
    try:
        # 这里写会触发异常的逻辑,比如除以0
        1 / sth
    except Exception:
        exception_handler("err_msg", print=False)

2. 修改测试文件的patch路径

把patch的目标改成test_target.exception_handler(也就是the_function所在模块里的引用):

import unittest
from unittest.mock import patch
from test_target import the_function

class Test_the_function(unittest.TestCase):
    @patch('test_target.exception_handler')  # 重点:这里的路径是被测试函数所在模块的引用
    def test_function_calls_exception_handler(self, mock_handler):
        the_function(0)  # 传入0触发异常,让the_function调用exception_handler
        # 断言函数被调用
        self.assertTrue(mock_handler.called)
        # 更严谨的断言:验证调用参数是否正确
        mock_handler.assert_called_once_with("err_msg", print=False)

额外验证技巧

如果还是不确定patch路径对不对,可以在测试里打印一下the_function.__module__,确认被测试函数所在的模块,然后把patch路径设为{模块名}.exception_handler。

另外,用assert_called_once_with比单纯的assertTrue(mock.called)更靠谱,能同时验证调用参数是否符合预期,避免误判。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 06:39:01