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??

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.