Skip to main content
Albero Academy

unittest

Write tests with Python's built-in testing framework.

Testing9 min

Automated tests verify your code does what you think — and keep doing it as you change things. Tests are what let you refactor fearlessly. unittest is Python's built-in, batteries-included test framework, modelled on the classic xUnit style.

Tests in a TestCase

Tests are methods named test_* on a TestCase subclass. Each uses assert* methods to check expectations:

unittest
import unittest
def add(a, b):
return a + b
class TestAdd(unittest.TestCase):
def test_positives(self):
self.assertEqual(add(2, 3), 5)
def test_negatives(self):
self.assertEqual(add(-1, -1), -2)
def test_type_error(self):
with self.assertRaises(TypeError):
add(1, "x")
if __name__ == "__main__":
unittest.main()

Assertions & fixtures

Common assertions: assertEqual, assertTrue, assertIn, assertRaises. Use setUp to build test data before each test and tearDown to clean up after.

Key takeaways

  1. 01unittest is the built-in xUnit-style test framework.
  2. 02Tests are test_* methods on a TestCase subclass.
  3. 03assertEqual/assertTrue/assertIn/assertRaises check expectations.
  4. 04setUp/tearDown provide per-test fixtures.
  5. 05Structure tests as Arrange–Act–Assert; automated tests catch regressions.

Finished this chapter?

Mark it complete to track your progress through Python.