kashiraja kashiraja - 1 year ago 91
Python Question

assertRaises does not catch exception / does not complain about no exception

This code does not work as expected. I'm getting pass when expecting fail; and fail when expecting pass for assertRaises().


import unittest

class TestConnectDatabase(unittest.TestCase):
def test_close(self):
self.assertRaises(ReferenceError, self.close_database()) # <--- Problem #1

# Just a stub for brevity...
def close_database(self):
#raise Exception(ReferenceError) # <--- Problem #2

if __name__ == '__main__':

In this example the code passes the unit test even though the exception was not raised. If
is uncommented, the exception is just passed to command line and the test fails when it should pass.

Executing test using:
python -m test_db
python test_db.py

Answer Source

You're calling the method self.close_database, when you should just be passing a reference to it. Remove the parentheses e.g.

def test_close(self):
    self.assertRaises(ReferenceError, self.close_database)

Check out the docs for more details.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download