Skip to content

Introduction to Python’s unittest Library

What is unittest?

unittestunittest is Python’s built-in testing framework.

It provides:

  • the TestCaseTestCase class
  • assertion methods (assertEqualassertEqual, assertTrueassertTrue, …)
  • test discovery
  • setup/teardown hooks

Core building blocks

  • TestCase: a class that contains test methods
  • test method: any method starting with test_test_
  • assertions: checks that validate expected behavior

Minimal example

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()
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()

How unittest runs tests

unittestunittest:

  • finds test classes derived from unittest.TestCaseunittest.TestCase
  • finds methods starting with test_test_
  • runs them and reports failures/errors

When to use unittest

  • 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.)

πŸ§ͺ Try It Yourself

Exercise 1 – Write a unittest TestCase

Exercise 2 – assertRaises

Exercise 3 – setUp and tearDown

If this helped you, consider buying me a coffee β˜•

Buy me a coffee

Was this page helpful?

Let us know how we did