【发布时间】:2023-04-06 02:31:02
【问题描述】:
我想知道如何在 Python 中断言引发的异常?我用 assertRaises(ExpectedException) 进行了尝试,但测试失败了,控制台输出告诉我引发了预期的异常。
那么我该如何写这个,以便捕获并断言异常呢?
【问题讨论】:
标签: python assert python-unittest
我想知道如何在 Python 中断言引发的异常?我用 assertRaises(ExpectedException) 进行了尝试,但测试失败了,控制台输出告诉我引发了预期的异常。
那么我该如何写这个,以便捕获并断言异常呢?
【问题讨论】:
标签: python assert python-unittest
如果抛出异常的模块和您的测试代码引用不同命名空间中的异常,就会发生这种情况。
例如,如果您有:
# 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)【讨论】:
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?。
【讨论】: