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

Python Unittest异常未抛出问题求助:测试异常代码块失败

问题分析与解决方案

核心问题在于你的create_df函数内部已经通过try-except块捕获了异常,所以当你模拟random.randint抛出异常时,异常只会在函数内部被处理,不会向外传播。self.assertRaises(Exception)是用来检测函数向外抛出的异常,自然会断言失败。

正确的测试思路

你需要测试的是函数在捕获异常后的处理逻辑是否符合预期,而非检测异常是否被抛出。以下是两种常见的测试方案:

方案1:验证异常处理后的返回值

如果create_df在捕获异常后会返回特定值(比如None或默认DataFrame),直接断言返回结果:

# 示例create_df函数实现
import random
import pandas as pd

def create_df():
    try:
        count = random.randint(1, 10)
        return pd.DataFrame({"value": range(count)})
    except Exception as e:
        print(f"处理异常: {str(e)}")
        return None

对应的测试代码:

from unittest import TestCase, mock

class TestCreateDF(TestCase):
    @mock.patch("random.randint")
    def test_create_df_handles_exception(self, mock_randint):
        # 模拟抛出异常
        mock_randint.side_effect = Exception("Random Error")
        
        # 断言函数返回预期的处理结果
        result = create_df()
        self.assertIsNone(result)

方案2:验证异常处理时的日志/输出

如果函数捕获异常后会打印日志或输出信息,可以通过捕获日志来验证异常是否被正确处理:

# 修改create_df使用logging输出日志
import logging
logging.basicConfig(level=logging.ERROR)

def create_df():
    try:
        count = random.randint(1, 10)
        return pd.DataFrame({"value": range(count)})
    except Exception as e:
        logging.error(f"捕获异常: {str(e)}")
        return None

对应的测试代码:

from unittest import TestCase, mock

class TestCreateDF(TestCase):
    @mock.patch("random.randint")
    def test_create_df_logs_exception(self, mock_randint):
        mock_randint.side_effect = Exception("Random Error")
        
        # 捕获日志并验证内容
        with self.assertLogs(level="ERROR") as log_context:
            create_df()
        
        self.assertIn("捕获异常: Random Error", log_context.output[0])

特殊情况:如果需要测试异常抛出

如果你确实需要验证函数在某些场景下会向外抛出异常,那需要调整create_df的设计——比如只捕获特定类型的异常,而非所有Exception,或者增加参数控制是否抑制异常。例如:

def create_df(raise_exceptions=False):
    try:
        count = random.randint(1, 10)
        return pd.DataFrame({"value": range(count)})
    except Exception as e:
        if raise_exceptions:
            raise
        logging.error(f"捕获异常: {str(e)}")
        return None

此时测试异常抛出的代码就能生效:

@mock.patch("random.randint")
def test_create_df_raises_exception(self, mock_randint):
    mock_randint.side_effect = Exception("Random Error")
    self.assertRaises(Exception, create_df, raise_exceptions=True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 10:15:01