0

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'

How can i test the exception part??

JDK
  • 217
  • 1
  • 10
  • 1
    This might be a duplicate of https://stackoverflow.com/questions/129507/how-do-you-test-that-a-python-function-throws-an-exception. – Oscar Mar 24 '22 at 09:01

1 Answers1

1

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.

Iguananaut
  • 21,810
  • 5
  • 50
  • 63