โ unittest: TestCase, assertEqual, setUp, discoveryLESSON~15 min
Testing with unittest
Python's unittest module is part of the standard library and provides a complete framework for writing and running automated tests. Good tests catch bugs before users do and give you confidence to refactor code.
The Structure of a Test
Every test file imports unittest, defines a class that inherits from unittest.TestCase, and writes methods whose names start with test_:
The class name conventionally starts with Test and describes what you're testing. Each test_* method tests one specific scenario.
Running Tests
Test discovery looks for files matching test*.py in the current directory and subdirectories.
Assertion Methods
unittest.TestCase provides many assertion methods. When an assertion fails, the test immediately stops and reports the failure:
assertRaises โ Testing Exceptions
Use assertRaises to verify that code raises the expected exception:
setUp and tearDown
setUp() runs before each test method. tearDown() runs after each test method, even if the test fails. Use them to prepare and clean up shared state:
setUpClass and tearDownClass
Run once for the entire class, not before each test. Use for expensive setup like database connections:
Organizing Test Files
Conventional project structure:
Each module gets a corresponding test file. Run all tests from the project root:
Skipping Tests
A Complete Example
Here's a real-world test for a simple BankAccount class:
Knowledge Check
What naming convention must test methods follow for unittest to discover them?
What is the purpose of setUp() in a unittest.TestCase class?
How do you verify that a function raises a specific exception in unittest?