简体   繁体   中英

How to assertRaises in unittest an exception caught in try except block?

In my production function:

def myfunction():
   try:
        do_stuff()
        (...)
        raise MyException("...")
    except MyException as exception:
         do_clean_up(exception)

My test fails, because the exception is caught in the try/except block

def test_raise(self):
   with self.assertRaises(MyException):
       myfunction()

self.assertRaises is never called.

How to guarantee that the exception is caught during testing?

The exception is never asserted AssertionError: MyException not raised

This is because you caught the exception MyException direct in myFunction() .

Comment out out the try-except clause and try again, test should pass.

assertRaises is used for uncaught errors. You can also re-raise in except block.

The exception is handled internally, so there is no external evidence that the exception is raised.

However, both MyException and do_clean_up are external names, which means you can patch them and make assertions about whether they do or do not get used. For example,

# Make sure the names you are patching are correct
with unittest.mock.patch('MyException', wraps=MyException) as mock_exc, \
     unittest.mock.patch('do_clean_up', wraps=do_clean_up) as mock_cleanup:
    myfunction()
    if mock_exc.called:
        mock_cleanup.assert_called()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM