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

如何在一个pytest.raises块中测试多个函数均抛出指定异常?

如何确保多个函数均抛出指定异常(pytest)

你当前的写法存在明显问题:只要第一个函数抛出ValueError,代码就会直接跳出pytest.raises上下文,第二个函数根本不会被执行,自然无法验证它是否也会抛出目标异常。要实现两个函数都抛出ValueError的验证需求,推荐以下几种方案:

方案1:分开使用独立的pytest.raises块

最直观的写法,给每个函数单独分配异常验证上下文:

def test_both_raise_value_error():
    with pytest.raises(ValueError):
        do_first_thing()
    with pytest.raises(ValueError):
        do_second_thing()

这样两个函数都会被执行,且各自的异常都会被单独验证,任意一个不抛出异常都会导致测试失败。

方案2:用参数化测试批量验证

如果需要验证的函数数量较多,用参数化测试更简洁,也便于后续扩展:

import pytest

@pytest.mark.parametrize("target_func", [do_first_thing, do_second_thing])
def test_functions_raise_value_error(target_func):
    with pytest.raises(ValueError):
        target_func()

pytest会自动遍历参数列表里的每个函数,分别执行测试逻辑,相当于自动生成多个独立的测试用例。

方案3:手动捕获异常(不推荐)

如果特殊场景下需要手动控制异常检查逻辑,可以用try-except配合pytest.fail:

def test_both_raise_value_error():
    # 验证第一个函数
    try:
        do_first_thing()
        pytest.fail("do_first_thing()未抛出预期的ValueError")
    except ValueError:
        pass

    # 验证第二个函数
    try:
        do_second_thing()
        pytest.fail("do_second_thing()未抛出预期的ValueError")
    except ValueError:
        pass

这种写法繁琐冗余,仅在无法使用前两种方案的特殊场景下考虑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 07:42:33