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.)
π§ͺ 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
