Introduction to Python’s unittest Library
What is unittest?
Section titled “What is unittest?”unittest is Python’s built-in testing framework.
It provides:
- the
TestCaseclass - assertion methods (
assertEqual,assertTrue, …) - test discovery
- setup/teardown hooks
Core building blocks
Section titled “Core building blocks”- TestCase: a class that contains test methods
- test method: any method starting with
test_ - assertions: checks that validate expected behavior
Minimal example
Section titled “Minimal example”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
Section titled “How unittest runs tests”unittest:
- finds test classes derived from
unittest.TestCase - finds methods starting with
test_ - runs them and reports failures/errors
When to use unittest
Section titled “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
Section titled “Visualize it”Every test method in a TestCase runs between a fresh setUp() and 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
Section titled “🧪 Try It Yourself”Exercise 1 – Write a unittest TestCase
Section titled “Exercise 1 – Write a unittest TestCase”Exercise 2 – assertRaises
Section titled “Exercise 2 – assertRaises”Exercise 3 – setUp and tearDown
Section titled “Exercise 3 – setUp and tearDown”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading