Home > database >  How to test exception part in unnitest python
How to test exception part in unnitest python

Time:03-24

I want to test the exception part of my code.

def main():
    try:
        logger.info("Ejecución planificada proceso Mae_CIL")
        a = ObjectA()
        a.method()
        logger.info("Success")
    except Exception as e:
        logger.error("Error: %s" % e)


@mock.patch.object(ObjectA, 'method')
def test_main(self, mock_method):
    # Case 1: Success
    mock_method.return_value = None
    main()
    self.assertEqual(1, 1)

    # Case 2: Test Exception
    mock_method.return_value = Exception
    self.assertRaises(Exception, main)

The Case 1 test the main method. And the Case 2 test the exception but the test fail with this message 'Exception: Exception not raised by main_Mae_UPR'

How can i test the exception part??

CodePudding user response:

As you found, just setting return_value to an exception doesn't cause that exception to be raised. That's because an exception is not a return--it's a completely different execution context that almost by definition means your function does not return. It's also possible to write a function that returns an exception object (or class as in your example).

You want Mock.side_effect.

  • Related