You need to enable JavaScript to run this app. Python3如何mock自定义异常?unittest测试报TypeError怎么解决
优惠活动
大模型
产品
解决方案
定价
更多

Python3如何mock自定义异常?unittest测试报TypeError怎么解决

问题根因

你完全没必要mockClusterException本身,这是报错的核心原因:

  • 你在测试代码中用mock.patch('src.ClusterException')把src模块导入的真实ClusterException异常类替换成了Mock对象
  • 当src.py的except ClusterException as e分支运行时,此时的ClusterException是被替换后的Mock实例,它没有继承Python的BaseException类,不符合异常捕获的语法要求,直接触发TypeError
  • 额外存在语法问题:你的src.py里第二个except分支except Exception:后raise时用到了变量e,但是你没给这个except分支绑定e变量,运行时会触发NameError。
修复方案

1. 先修复src.py的语法错误

# src.py 修正后
from exceptions import ClusterException, IndexingException
from utils import create_index, index_to_es
# 注意你代码中的get_object、index_name等变量需确保实际有定义,此处省略无关逻辑
def method(bucket, key, file):
    try:
       s3_obj = get_object(bucket, key)
       # 省略其他业务逻辑
       create_index(index_name, index_mapping)
       index_to_es(df)
    except ClusterException as e:
       raise ClusterException(e)
    except Exception as e: # 此处补充as e绑定异常变量,避免后续e未定义
       raise IndexingException(e)

2. 修正测试代码

删掉对ClusterException的mock,你只需要mockcreate_index让它抛出真实的ClusterException即可,异常类本身无外部依赖不需要mock:

# test_src.py 修正后
from exceptions import ClusterException
import unittest.mock as mock
# 此处假设代码写在unittest的Test类测试方法中
def test_cluster_exception_catch(self):
    with mock.patch('src.create_index') as mocked_create_index:
        # 让被mock的create_index抛出真实的自定义异常
        mocked_create_index.side_effect = ClusterException("Index creation error")
        self.assertRaises(ClusterException, method, 'bucket', 'key', 'file')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 18:33:01