You need to enable JavaScript to run this app. 如何使用pytest测试try/except块异常捕获后的执行逻辑
优惠活动
大模型
产品
解决方案
定价
更多

如何使用pytest测试try/except块异常捕获后的执行逻辑

测试try/except内部异常处理逻辑的实现方案

你遇到的报错原因是:AssertionError已经在my_func内部被except块捕获处理,不会向外抛出到测试函数的调用层,因此pytest.raises无法捕获到该异常。如果需要验证异常捕获后的执行逻辑,可以参考以下两种方案:


方案1:使用pytest内置capsys fixture捕获标准输出(适合验证打印内容的场景)

capsys是pytest官方提供的内置fixture,可直接捕获程序向标准输出/标准错误流打印的内容,无需修改原有业务代码,适配你当前的测试需求:

import pytest

def my_func(string):
    try:
        assert string == "pass"
        print("String is `pass`")
    except AssertionError:
        print("String is not 'pass'")

def test_my_func_exception_case(capsys):
    # 触发AssertionError分支
    my_func("fail")
    # 捕获标准输出内容
    captured = capsys.readouterr()
    # 断言输出符合预期,strip()用于去除末尾自动添加的换行符
    assert captured.out.strip() == "String is not 'pass'"

def test_my_func_normal_case(capsys):
    # 测试正常分支的输出
    my_func("pass")
    captured = capsys.readouterr()
    assert captured.out.strip() == "String is `pass`"

如果存在多个except分支,只需要构造不同的入参触发对应分支,再重复捕获输出、断言的逻辑即可,不需要额外修改测试逻辑。


方案2:抽离异常处理后的业务逻辑(适合复杂业务场景,可维护性更高)

如果except块内不止有打印操作,还有其他业务处理逻辑,建议把处理逻辑抽为独立函数,直接测试逻辑返回值即可,不需要依赖输出捕获:

import pytest

# 抽离异常处理逻辑
def handle_assertion_error():
    msg = "String is not 'pass'"
    print(msg)
    # 有其他业务逻辑也可以放在这里
    return msg

def my_func(string):
    try:
        assert string == "pass"
        print("String is `pass`")
    except AssertionError:
        handle_assertion_error()

def test_handle_assertion_error():
    # 直接测试异常处理函数的返回值/行为,不需要依赖my_func的调用
    result = handle_assertion_error()
    assert result == "String is not 'pass'"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 08:45:03