I have the following test-code checking for an exception raising in a function. I expect the test to pass, but a failure is indicated instead. Here is the test code:
import unittest
# define a user-defined exception
class MyException(Exception):
def __str__(self):
return repr("ERROR: Just raised my exception!")
# this is my main class with a method raising this exception
class MyMainObject(object):
def func(self):
raise MyException()
# the test class
class TestConfig(unittest.TestCase):
def test_1(self):
other = MyMainObject()
self.assertRaises(MyException, other.func())
# calling the test
if __name__ == '__main__':
unittest.main()
When other.func() is called in the assert statement, MyException is raised (can be checked easily). So, the assertRaises test should pass the test, as other.func() failes with MyException, BUT:
....
MyException: 'ERROR: Just raised my exception!'
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (errors=1)
I do not see something wrong, so I would appreciate some input on this problem.
assertRaisescalls the function for you. By calling it yourself, the exception is raised beforeassertRaisescan test it.Change your code to:
and it’ll work correctly. Alternatively, you can use
assertRaisesas a context manager (python 2.7 and up):Using
assertRaisesas a context manager has the added advantage that you can now retrieve the exception instance and perform further tests on it: