assertRaises in python unit-test not catching the exception [duplicate]

妖精的绣舞 提交于 2019-11-27 03:48:04

问题


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.

I'm using Python 2.7.5 on a linux box.

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)

回答1:


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

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:

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


来源:https://stackoverflow.com/questions/25047256/assertraises-in-python-unit-test-not-catching-the-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!