Unit Testing with unittest

advanced level · ~20 min · Module 19: Testing & Quality Assurance

Verify code correctness automatically with TestCase assertions.

Learning objectives

  • Create test classes inheriting from unittest.TestCase
  • Use self.assertEqual, self.assertTrue, self.assertRaises

Lesson material

Testing Protocol

Unit tests test individual isolated functions or methods.

Example code

import unittest

def add(a, b):
    return a + b

class TestMath(unittest.TestCase):
    def test_add(self):
        self.assertEqual(add(2, 3), 5)
        self.assertEqual(add(-1, 1), 0)

suite = unittest.TestLoader().loadTestsFromTestCase(TestMath)
runner = unittest.TextTestRunner(verbosity=0)
res = runner.run(suite)
print("Tests Passed:", res.wasSuccessful())

Practice exercise: Write a Test Case

Write a unittest test case testing a function `is_even(n)` returning `True` for `4` and `False` for `5`.

Test yourself with the Module 19: Testing & Quality Assurance quiz →

View the full Python curriculum →