Sujit Devkar
Sujit Devkar

Reputation: 1215

Python Unittest: Unit test the message passed in raised exception

I am unit testing the radius of the circle using unittest framework in Python. If the radius is not a numeric value, then I raise and exception with a custom message.

File: circle.py

class Circle():

    def __init__(self, radius):
        if not isinstance (radius, (int,float)):
            raise TypeError('radius must be a number')
        else:
            self.radius = radius

File: test_circle.py

import unittest
from circle import Circle

class CircleTest(unittest.TestCase):

    def test_radius(self):
        c1 = Circle(2.5)
        self.assertEqual(c1.radius, 2.5)

    def test_radius_type(self):
        self.assertRaises(TypeError, Circle, 'hello')

if __name__ == "__main__":
    unittest.main()

Now, I can check the raised exception. But, I also want to find if the message passed in the exception is the exact message or not. Could anyone please guide me how to test and check the message passed in the exception in unittest in Python?

Upvotes: 2

Views: 8733

Answers (1)

chepner
chepner

Reputation: 532238

If you want to check the error message in the exception, you need to capture the exception.

def test_radius_type(self):
    with self.assertRaises(TypeError) as exc:
        c = Circle('hello')
    self.assertEquals(str(exc.exception), "radius must be a number")

That said, a custom exception would be cleaner.

class NotANumberError(TypeError):
    pass


class Circle:
    def __init__(self, radius):
        try:
            self.radius = float(radius)
        except ValueError:
            raise NotANumberError


...

def test_radius_type(self):
    self.assertRaises(NotANumber, Circle, 'hello')

The type of the exception itself carries the same information as an arbitrary error message.

Upvotes: 6

Related Questions