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.
assertRaises calls the function for you. By calling it yourself, the exception is raised before assertRaises can test it.
Change your code to:
self.assertRaises(MyException, other.func)
and it'll work correctly. Alternatively, you can use assertRaises as a context manager (python 2.7 and up):
with self.assertRaises(MyException):
    other.func()
Using assertRaises as a context manager has the added advantage that you can now retrieve the exception instance and perform further tests on it:
with self.assertRaises(MyException) as raises_cm:
    other.func()
exception = raises_cm.exception
self.assertEqual(exception.args, ('foo', 'bar'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With