Lesson 16: Writing Tests with unittest
The last lesson showed pytest, the test runner most teams choose. This lesson covers unittest, the testing framework that ships with Python itself. It is always available — no installation needed — and it is the framework you will meet in many codebases, so knowing it is a practical skill even if you prefer pytest day to day. Its style is different: tests live in classes that inherit from unittest.TestCase, test methods start with test_, and you check results with assert methods such as assertEqual and assertRaises.
The example below tests a small Calculator class. The setUp method runs before every test, building a fresh calculator, so each test starts clean. One test checks a normal result, one checks that dividing by zero raises the right exception, and the final block lets you run the file directly. Running it with python -m unittest test_calculator.py prints a reassuring row of dots — one per passing test — and a summary. A failing test prints a detailed report showing exactly which assert failed and why.
import unittest
class Calculator:
def add(self, a, b):
return a + b
def divide(self, a, b):
if b == 0:
raise ValueError("cannot divide by zero")
return a / b
class TestCalculator(unittest.TestCase):
def setUp(self):
self.calc = Calculator()
def test_add(self):
self.assertEqual(self.calc.add(2, 3), 5)
self.assertEqual(self.calc.add(-1, 1), 0)
def test_divide_by_zero(self):
with self.assertRaises(ValueError):
self.calc.divide(10, 0)
if __name__ == "__main__":
unittest.main()
What makes a good test
A good test checks one behaviour, has a clear name that says what it checks, and is independent of every other test. test_divide_by_zero does all three: it tests a single rule, its name states the rule, and it builds its own calculator in setUp, so it cannot be affected by another test's leftovers. Two more habits complete the picture. First, test the edges, not just the easy path: empty lists, zero, negative numbers, missing files. Second, test behaviour, not implementation: check that add(2, 3) returns 5, not how the method stores its variables. Tests written against behaviour survive refactoring; tests written against internals break every time you improve the code.
The deeper idea is test-driven development, or TDD: write the test first, watch it fail, then write the smallest code that makes it pass. It feels backwards at first, but it forces you to decide what the code should do before you decide how it does it, and it guarantees every feature arrives with a test. You do not need to follow TDD strictly to benefit from testing — even a small suite of tests, run before every change, transforms how confidently you can improve a program. That confidence is the real product of this unit.
Going further
The unittest module has a few more assert methods that cover the common checks. assertTrue and assertFalse check a condition directly; assertIn checks membership in a collection; assertAlmostEqual compares floating-point numbers to a given number of decimal places, which matters because floating-point arithmetic is rarely exact. Knowing these methods exist means your tests can say precisely what they mean, and the failure messages will show the values involved — which is usually enough to see the bug.
Running tests is half the workflow. The command python -m unittest -v runs with verbose output, naming each test as it passes. The discover subcommand, python -m unittest discover, finds and runs every test file in a project, which is what you want once the project has more than one test file. Many editors run discovery automatically and show a green tick beside each passing test. Whatever the interface, the habit is the same: run the tests before every commit, and never commit while a test is red.
A useful exercise is to write tests for a function you already trust — for example, the average function from Lesson 13 — and to include the cases that feel silly: an empty list, a list with one number, a list of negative numbers, a list with a very large number. The silly cases are the ones that find bugs, because they are the cases the original author never thought about. If a test fails on a case you considered silly, you have learned something real about the code — and the test you just wrote will protect the next person who changes it.
Watch & Learn
One video to watch for this unit, from a trusted educator.
- Python Tutorial: Unit Testing Your Code with the unittest Module — Corey Schafer
Corey writes unit tests with the standard library's unittest module, including setUp, tearDown and mocking with unittest.mock.
Key Terms
- unittest
- The testing framework built into Python's standard library, based on TestCase classes.
- TestCase
- The unittest base class; a test class inherits from it and its test methods start with test_.
- assertEqual
- A TestCase method that checks two values are equal, with a clear failure message if not.
- assertRaises
- A TestCase check (used as a context manager) that a block of code raises a given exception.
- setUp
- A method that runs before every test in a TestCase, building fresh objects for each test.
- tearDown
- A method that runs after every test, used to clean up resources created in setUp.
- Test-driven development (TDD)
- Writing a failing test first, then the smallest code that makes it pass.
Discussion Questions
- Why does setUp run before every test instead of once for the whole class? What bug would shared setup cause?
- When is it better to test behaviour rather than implementation? Give an example where an implementation test would break during a harmless refactor.
- Is test-driven development worth the extra time? When might writing the test first change what code you write?
Practice Questions
- How do you run the tests in
test_calculator.pyfrom the terminal? - What does
assertEqual(self.calc.add(2, 3), 5)check? - How does
assertRaisescheck that dividing by zero fails correctly? - Why is testing edge cases (empty lists, zero, negatives) important?
- Write a unittest test method that checks
Calculator().add(0, 0) == 0.
Show answers
python -m unittest test_calculator.py. The -m flag runs the unittest module, which discovers and runs the TestCase classes.- That add(2, 3) returns 5. If the values differ, the test fails with a message showing both values.
- It wraps the call in a with block and passes only if ValueError is raised. If no exception is raised, the test fails.
- Edge cases are where bugs hide; the easy path usually already works. A test suite that only checks happy paths gives false confidence.
def test_add_zero(self): self.assertEqual(Calculator().add(0, 0), 0)The method name starts with test_ so unittest discovers and runs it.