unittest 中的 assertRaises 未按预期运行

assertRaises in unittest not acting as expected

更新:我的问题实际上是关于理解 assertRaises 需要调用函数,而不是函数本身。这个问题类似于 post: How do you test that a Python function throws an exception? 但是特别询问为什么我的直接调用函数的代码不起作用。

我已经在此处检查了其他几个关于该主题的 post,但无法弄清楚哪里出了问题。 我试图断言将发生给定的异常。为了简单起见,我将其简化为一个非常基本的函数,该函数会引发异常类型。我已经尝试过 BaseException,但它也不起作用。我希望我遗漏了一些基本的东西。感谢您的帮助!

我是运行python3.9.1。复制的代码来自 jupyter notebook,但我使用纯 python 并从命令行调用时遇到相同的错误。

def raise_exception():
    raise ValueError

class Test_exceptions(unittest.TestCase):
    def test_exception(self):
        self.assertRaises(ValueError, raise_exception())

unittest.main(argv=[''],verbosity=2, exit=False)

输出:

test_exception (__main__.Test_exceptions) ... ERROR

======================================================================
ERROR: test_exception (__main__.Test_exceptions)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "<ipython-input-8-f1c9cab8fc2b>", line 6, in test_exception
    self.assertRaises(ValueError, raise_exception())
  File "<ipython-input-8-f1c9cab8fc2b>", line 2, in raise_exception
    raise ValueError
ValueError

----------------------------------------------------------------------
Ran 1 test in 0.002s

FAILED (errors=1)
<unittest.main.TestProgram at 0x22a27396550>

你的代码中的问题是你正在用这一行执行函数。

self.assertRaises(ValueError, raise_exception())

而它应该是 unittest 模块做同样的事情。

只需删除函数名称中的括号。

self.assertRaises(ValueError, raise_exception)