Test For A Specific Exception

Want to learn more? I recommend these Python books: Python for Data Analysis, Python Data Science Handbook, and Introduction to Machine Learning with Python.

Preliminaries

import unittest

Create A Function To Test

def add(x, y):
    return x + y

Create Test Case

# Create a test case
class TestAdd(unittest.TestCase):
    # Create the unit test
    def test_input_string(self):
        # Test To make sure a TypeError exception is raised
        self.assertRaises(TypeError, add('Banana', 'Boat'))

Run Test

# Run the unit test (and don't shut down the Jupyter Notebook)
unittest.main(argv=['ignored', '-v'], exit=False)
test_input_string (__main__.TestAdd) ... ok

----------------------------------------------------------------------
Ran 1 test in 0.002s

OK





<unittest.main.TestProgram at 0x104855320>