【问题标题】:How to assert a raised custom exception in Python with PyUnit?如何使用 PyUnit 在 Python 中断言引发的自定义异常?
【发布时间】:2023-04-06 02:31:02
【问题描述】:

我想知道如何在 Python 中断言引发的异常?我用 assertRaises(ExpectedException) 进行了尝试,但测试失败了,控制台输出告诉我引发了预期的异常。
那么我该如何写这个,以便捕获并断言异常呢?

【问题讨论】:

    标签: python assert python-unittest


    【解决方案1】:

    如果抛出异常的模块和您的测试代码引用不同命名空间中的异常,就会发生这种情况。

    例如,如果您有:

    # code_to_be_tested.py
    
    from module_with_exception import * # including CustomException
    
    ...
    
    raise CustomException()
    
    # test_code.py
    
    import module_with_exception.CustomException as CE
    
    ...
    
    with assertRaises(CE) ...
    

    这是因为这两个文件实际上最终指向不同的类/对象。


    所以,有两种解决方法:

    • 尽可能以相同的方式引用它们
    • 如果您执行from blah import * 之类的操作,请从测试模块本身 中获取异常,因为这是它引发的异常(即from code_to_be_tested import CustomException)

    【讨论】:

      【解决方案2】:

      AssertRaises() 可以测试您从代码中引发的所有异常。

      使用 assertRaises 的语法是:

      assertRaises(CustomException, Function that throws the exception, Parameters for function(In case of multiple params, they will be comma separated.))
      

      它是如何工作的:

      当遇到 assertRaises 时,pyUnit 会执行 Try-Except 块中提到的函数,而 except 块包含 CustomException。如果异常处理得当,则测试通过,否则失败。

      有关 assertRaises 的更多信息,请访问How to properly use unit-testing's assertRaises() with NoneType objects?。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-07-30
        • 1970-01-01
        • 1970-01-01
        • 2020-04-20
        • 2012-02-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多