Search code examples
djangodjango-unittest

asserting an error message matches a string in Django


Is this possible? I have an custom error message and I would like to check that it is raised when a validation is not met. Can I do something similar to the following?

self.assertEqual(ValidationError.message, 'name validation not met')


Solution

  • Yes, it's like this:

    with self.assertRaisesMessage(ValidationError, 'name validation not met'):
        # code that causes the exception
    

    To have the assertRaisesMessage helper available, you should be working within a Django TestCase.