在 pytest 中引发异常(失败:未引发 <class 'ValueError'>)

Raise exception in pytest (Failed: DID NOT RAISE <class 'ValueError'>)

我在 unitest 代码中捕获异常时遇到问题。 以下是我的代码

def get_param(param)        
    if param is None:
        raise ValueError('param is not set')

def test_param():
    with pytest.raises(ValueError) as e:
        get_param()

问题是当函数不引发异常时,test_param() 会失败并出现以下错误。

Failed: DID NOT RAISE <class 'ValueError'>

当 get_param(param) 函数抛出异常时,它按预期工作。

没问题,python.raises 正常工作。通过使用它,您可以断言某个异常。 如果你真的不想得到异常,你可以使用 try-except 来捕获并抑制它,就像这样:

from _pytest.outcomes import Failed

def test_param():
    try:
        with pytest.raises(ValueError):
            get_param()
    except Failed as exc:
        # suppress
        pass
        # or
        # do something else with the exception
        print(exc)
        # or
        raise SomeOtherException

我遇到了同样的问题。这个解决方案对我有用。

        try:
            with pytest.raises(ValidationError) as excinfo:
                validate_bank_account_number(value=value)
            assert excinfo.value.args[0] == 'your_error_message_returned_from_validation_error'
        except:
            assert True