Python unit testing sys.exit call with assertRaises or mock.patch

615 Views Asked by At

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?

0

There are 0 best solutions below