Home > python > Unittest using assertRaises

Unittest using assertRaises

Problem:
I needed to test that a function returns an exception.

Solution:
Sample code

# sample.py
def sum(a, b):
    total = None
    try:
        total = a + b
    except TypeError:
        raise TypeError("Integers only")

    return total

and

# test_assert.py
import unittest

from sample import sum


class TestSum(unittest.TestCase):
    def test_total(self):
        self.assertEquals(sum("3", 2), 4)

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

Running the test to check that an assert is raised

$ python test_assert.py
E
======================================================================
ERROR: test_total (__main__.TestSum)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test_assert.py", line 7, in test_total
    self.assertEquals(sum("3", 2), 4)
  File "/Users/rodnee/sample.py", line 6, in sum
    raise TypeError("Integers only")
TypeError: Integers only

----------------------------------------------------------------------
Ran 1 test in 0.000s

Changing the unit test to catch the raised exception

# test_assert.py
import unittest

from sample import sum


class TestSum(unittest.TestCase):
    def test_total(self):
        self.assertEquals(sum(2, 2), 4)
        # First argument is the Exception to be caught ie TypeError
        # Second argument is the method under test ie sum
        # Third to x arguments are the values to pass onto sum()
        self.assertRaises(TypeError, sum, "3", 2)

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

Running the updated unit test produces

$ python test_assert.py
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

Source:
http://www.lengrand.fr/2011/12/pythonunittest-assertraises-raises-error/
https://pymotw.com/2/exceptions/
http://eu.wiley.com/WileyCDA/WileyTitle/productCd-1118901223.html

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: