01 / 20

Python
unittest Framework

Learn to write automated tests for your Python code using the built-in unittest module: test cases, assertions, and running test suites.

Python

What is Software Testing?

Software testing is the process of verifying that your code works correctly. Instead of manually running your program and checking the output every time, you write small programs called tests that check your code automatically.

Why Use unittest?

Built-in
Ships with every Python installation: no extra packages to install.
Structured
Organizes tests into classes and methods with a clear, repeatable pattern.
Powerful
Provides dozens of assertion methods, setup/teardown hooks, and test discovery.

Key Vocabulary

1
Test Case: A single unit of testing: one class that groups related test methods together.
2
Test Method: A function inside a test case whose name starts with test_. Each method checks one behavior.
3
Assertion: A check that compares an expected value with an actual value and raises an error if they differ.
4
Test Runner: The tool that finds, runs, and reports the results of your tests.

The Core Structure

import unittest class TestMyCode(unittest.TestCase): Test Methods def test_add(self): def test_subtract(self): unittest.main() runs all tests

Essential Assertions

Method Checks That
assertEqual(a, b) \(a == b\)
assertNotEqual(a, b) \(a \neq b\)
assertTrue(x) x is True
assertFalse(x) x is False
assertIn(a, b) a is in b
assertRaises(Error) Error is raised

assertEqual vs assertTrue

assertEqual(a, b)
Compares two values directly. On failure, tells you exactly what both values were: "Expected 5, got 7".
assertTrue(expr)
Only checks if an expression is truthy. On failure, just says "False is not true": much less helpful.

How to Write a Test

1
Create a file named test_*.py (e.g., test_math_ops.py). The test_ prefix is required for auto-discovery.
2
Import unittest and the module you want to test.
3
Define a class that inherits from unittest.TestCase.
4
Write methods starting with test_. Each should call at least one assertion.
5
Run your tests with python -m unittest or add unittest.main() at the bottom.

Example 1: Your First Test

# math_ops.py def add(a, b): return a + b
# test_math_ops.py import unittest from math_ops import add class TestAdd(unittest.TestCase): def test_positive_numbers(self): self.assertEqual(5, add(2, 3)) def test_negative_numbers(self): self.assertEqual(-2, add(-1, -1)) if __name__ == '__main__': unittest.main()

Example 2: Edge Cases

def divide(a, b): if b == 0: raise ValueError("Cannot divide by zero") return a / b
class TestDivide(unittest.TestCase): def test_basic_division(self): self.assertEqual(5, divide(10, 2)) def test_float_result(self): self.assertAlmostEqual(divide(1, 3), 0.333, places=2) def test_divide_by_zero(self): with self.assertRaises(ValueError): divide(5, 0)

Example 3: setUp and tearDown

class TestShoppingCart(unittest.TestCase): def setUp(self): # Runs BEFORE each test method self.cart = ShoppingCart() self.cart.add_item("apple", 1.50) def test_item_count(self): self.assertEqual(1, self.cart.count()) def test_total_price(self): self.cart.add_item("banana", 0.75) self.assertEqual(2.25, self.cart.total()) def tearDown(self): # Runs AFTER each test method self.cart.clear()

Running Your Tests

Command Line
python -m unittest test_math_ops
Discovers and runs all test_ methods in the file.
Verbose Mode
python -m unittest -v
Shows each test name and its result: OK, FAIL, or ERROR.
Auto-Discovery
python -m unittest discover
Finds all test_*.py files in the directory automatically.

Reading Test Output

$ python -m unittest -v test_math_ops test_positive_numbers ... ok test_negative_numbers ... ok test_broken_feature ... FAIL ---------------------------------------------------------------------- FAIL: test_broken_feature (test_math_ops.TestAdd) AssertionError: 4 != 5 ---------------------------------------------------------------------- Ran 3 tests in 0.001s FAILED (failures=1)

The Test Lifecycle

setUp() prepare state test_method() run assertions tearDown() clean up Repeats for EACH test method PASS FAIL ERROR possible outcomes

Common Mistakes

✕ Missing test_ Prefix
Naming a method check_add instead of test_add. The runner only discovers methods starting with test_.
✕ Forgetting self
Writing assertEqual(a, b) instead of self.assertEqual(a, b). Assertions are methods on the TestCase class.
✕ Confusing Argument Order
The standard convention is self.assertEqual(expected, actual). While the other order works, this is more readable ("expected 5, got result") and consistent with other testing frameworks.

Quick Reference Summary

Concept Syntax / Rule Purpose
Test File test_*.py Auto-discovery
Test Class class X(unittest.TestCase) Groups related tests
Test Method def test_*(self) One behavior check
Assertion self.assertEqual(a, b) Verify expected result
setUp / tearDown def setUp(self) Prepare / clean state
Run Tests python -m unittest Execute all tests

Question 1 of 5

To create a test case class in unittest, your class must inherit from:

Question 2 of 5

Which test method name will be discovered and run automatically by the unittest runner?

Question 3 of 5

What does self.assertEqual(5, add(2, 3)) do if add(2, 3) returns 6?

Question 4 of 5

What is the purpose of the setUp method in a test case?

Question 5 of 5

You want to verify that calling divide(10, 0) raises a ValueError. Which is the correct approach?