Unit Testing with unittest
unittest is Python's built-in testing framework. Write test cases, assertions, setUp/tearDown, and organize tests.
20 min•By Priygop Team•Updated 2026
unittest
unittest
import unittest
# Code to test
def add(a, b):
return a + b
def divide(a, b):
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
def is_palindrome(text):
clean = text.lower().replace(" ", "")
return clean == clean[::-1]
# Test class
class TestMathFunctions(unittest.TestCase):
def setUp(self):
"""Runs before each test."""
self.data = [1, 2, 3, 4, 5]
def test_add_positive(self):
self.assertEqual(add(2, 3), 5)
def test_add_negative(self):
self.assertEqual(add(-1, -1), -2)
def test_add_zero(self):
self.assertEqual(add(0, 0), 0)
def test_divide(self):
self.assertAlmostEqual(divide(10, 3), 3.333, places=2)
def test_divide_by_zero(self):
with self.assertRaises(ValueError):
divide(10, 0)
def test_palindrome(self):
self.assertTrue(is_palindrome("racecar"))
self.assertTrue(is_palindrome("A man a plan a canal Panama"))
self.assertFalse(is_palindrome("hello"))
# Run tests
print("=== Running Tests ===")
suite = unittest.TestLoader().loadTestsFromTestCase(TestMathFunctions)
runner = unittest.TextTestRunner(verbosity=2)
runner.run(suite)
# Key assertions:
# assertEqual(a, b) — a == b
# assertNotEqual(a, b) — a != b
# assertTrue(x) — bool(x) is True
# assertFalse(x) — bool(x) is False
# assertRaises(Error) — exception raised
# assertIn(a, b) — a in b
# assertIsNone(x) — x is None
# assertAlmostEqual(a, b) — a ≈ bTip
Tip
Name test files test_*.py and test functions test_*. Use descriptive names: test_user_creation_with_valid_email.
Diagram
Loading diagram…
pytest > unittest. Use fixtures for DRY. Mock external services. Run in CI with tox for multi-version.
Common Mistake
Warning
Testing implementation details instead of behavior. Test WHAT the code does, not HOW it does it. This makes tests resilient to refactoring.
Quick Quiz
Practice Task
Note
(1) Write tests for a simple calculator. (2) Test edge cases (0, negative, large numbers). (3) Run tests with python -m unittest.