[Solved]-How to correctly use assertRaises in Django

29👍

The way you are calling assertRaises is wrong – you need to pass a callable instead of calling the function itself, and pass any arguments to the function as arguments to assertRaises. Change it to:

self.assertRaises(ValidationError, w.validate_kind, 'test')

7👍

The accepted answer isn’t correct. self.assertRaises() doesn’t check the exception message.

Correct answer

If you want to assert the exception message, you should use self.assertRaisesRegex().

self.assertRaisesRegex(ValidationError, 'Invalid question kind', w.validate_kind, 'test')

or

with self.assertRaisesRegex(ValidationError, 'Invalid question kind'):
    w.validate_kind('test')

1👍

I would do:

with self.assertRaises(ValidationError, msg='Invalid question kind'):
    w.validate_kind('test')

This may well be a change in Python since the question was originally asked.

Leave a comment