Introduction to Python’s unittest Library
What is unittest?
unittestunittest is Python’s built-in testing framework.
It provides:
- the
TestCaseTestCaseclass - 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.)
Visualize it
Every test method in a TestCaseTestCase runs between a fresh setUp()setUp() and tearDown()tearDown() call, so each test starts and ends in a known state.
flowchart TD A["setUp()"] --> B["Test method (assertions)"] B --> C["tearDown()"] C --> D["Repeat for each test method"] D --> A
🧪 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 coffeeWas this page helpful?
Let us know how we did
