【问题标题】:How to assertRaises in unittest an exception caught in try except block?如何在 unittest 中断言在 try except 块中捕获异常?
【发布时间】:2022-11-29 03:37:47
【问题描述】:

在我的 Python 函数中:

`def myfunction():
   try:
        do_stuff()
        (...)
        raise MyException("...")
    except MyException as exception:
         do_clean_up(exception)`

我的测试失败了,因为在 try/except 块中捕获了异常

`def test_raise(self):
   with self.assertRaises(MyException):
       myfunction()`

self.assertRaises 永远不会被调用。

如何保证在测试时捕获到异常?

永远不会断言异常 AssertionError: MyException not raised

【问题讨论】:

    标签: python unit-testing exception python-unittest


    【解决方案1】:

    这是因为您在 myFunction 中捕获了它。注释掉 except 子句并重试,测试应该通过。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多