Skip to content

Introduction to Python’s unittest Library

unittest is Python’s built-in testing framework.

It provides:

  • the TestCase class
  • assertion methods (assertEqual, assertTrue, …)
  • test discovery
  • setup/teardown hooks
  • TestCase: a class that contains test methods
  • test method: any method starting with test_
  • assertions: checks that validate expected behavior
test_math_unittest.py
import unittest
 
 
def add(a, b):
    return a + b
 
 
class TestAdd(unittest.TestCase):
    def test_add_two_numbers(self):
        self.assertEqual(add(2, 3), 5)
 
 
if __name__ == "__main__":
    unittest.main()

unittest:

  • finds test classes derived from unittest.TestCase
  • finds methods starting with test_
  • runs them and reports failures/errors
  • you want zero external dependencies
  • you’re working in legacy codebases already using unittest

(Modern projects often prefer pytest; we cover it in Phase 4.)

Every test method in a TestCase runs between a fresh setUp() and tearDown() call, so each test starts and ends in a known state.

diagram unittest Test Lifecycle mermaid
setUp() and tearDown() wrap around every individual test method.

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading