1

I've read a lot of answers suggesting that the way to unit test sys.exit is to do the following:

with self.assertRaises(SystemExit) as system_exit:
    function()
self.assertEqual(system_exit.exception_code, 1)

Does the above not actually raise a SystemExit in my test? Is it better or worse to do the following?

@mock.patch("<path to class file>.sys.exit")
def testFunction(self, mock_sys_exit):
    function()
    mock_sys_exit.assert_called_once_with(1)

Are both the approaches equivalent, or is one better than the other? And why?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
cubestack
  • 11
  • 1
  • Use whatever works best for you. That being said I would prefer `asserRaises` because it is more explicit IMHO, but that is just me. – MrBean Bremen Mar 26 '20 at 17:11

0 Answers0