),python,pytest,python-unittest,valueerror"/>

首页 > 解决方案 > 在 pytest 中引发异常(失败:DID NOT RAISE)

问题描述

在我的 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) 函数抛出异常时,它按预期工作。

标签: pythonpytestpython-unittestvalueerror

解决方案


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

        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

推荐阅读