python单元测试中的assertRaises未捕获异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25047256/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 19:38:31  来源:igfitidea点击:

assertRaises in python unit-test not catching the exception

pythonunit-testingassertraises

提问by user3014653

Can somebody tell me why the following unit-test is failing on the ValueError in test_bad, rather than catching it with assertRaises and succeeding? I think I'm using the correct procedure and syntax, but the ValueError is not getting caught.

有人能告诉我为什么下面的单元测试在 test_bad 的 ValueError 上失败,而不是用 assertRaises 捕获它并成功吗?我想我使用了正确的过程和语法,但是 ValueError 没有被捕获。

I'm using Python 2.7.5 on a linux box.

我在 linux 机器上使用 Python 2.7.5。

Here is the code …

这是代码……

import unittest

class IsOne(object):
    def __init__(self):
        pass
    def is_one(self, i):
        if (i != 1):
            raise ValueError

class IsOne_test(unittest.TestCase):

    def setUp(self):
        self.isone = IsOne()

    def test_good(self):
        self.isone.is_one(1)
        self.assertTrue(True)

    def test_bad(self):
        self.assertRaises(ValueError, self.isone.is_one(2))

if __name__ == "__main__":
    unittest.main()

and here is the output of the unit-test:

这是单元测试的输出:

======================================================================
ERROR: test_bad (__main__.IsOne_test)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test/raises.py", line 20, in test_bad
    self.assertRaises(ValueError, self.isone.is_one(2))
  File "test/raises.py", line 8, in is_one
    raise ValueError
ValueError

----------------------------------------------------------------------
Ran 2 tests in 0.008s

FAILED (errors=1)

回答by Gerrat

Unittest's assertRaisestakes a callable and arguments, so in your case, you'd call it like:

Unittest 的assertRaises需要一个可调用对象和参数,因此在您的情况下,您可以这样称呼它:

self.assertRaises(ValueError, self.isone.is_one, 2)

If you prefer, as of Python2.7, you could also use it as a context manager like:

如果您愿意,从 Python2.7 开始,您还可以将其用作上下文管理器,例如:

with self.assertRaises(ValueError):
    self.isone.is_one(2)