Search code examples
djangopython-unittestdjango-testingdjango-testsdjango-errors

How to correctly use assertRaises in Django


I have the following validation function in my model:

@classmethod
def validate_kind(cls, kind):
    if kind == 'test':
        raise ValidationError("Invalid question kind")

which I am trying to test as follows:

w = Model.objects.get(id=1) 

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

I also tried:

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

Both of these don't work correctly. What am I doing wrong?


Solution

  • 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')