How to Write Unit Tests in Python: A Step-by-Step Tutorial
Unit tests help you verify that individual parts of your code work correctly. Python’s built-in unittest module makes testing straightforward. This tutorial covers the essentials so you can start writing reliable tests in minutes.
First, create a Python file for your unit tests (e.g., test_calculator.py). Import the unittest module and the code you want to test. Then define a test class that inherits from unittest.TestCase.
1. Structure a Test Case
Inside your test class, write methods whose names begin with test_. Each method should test one specific behavior. For example:
import unittest
from calculator import add
class TestCalculator(unittest.TestCase):
def test_add(self):
result = add(2, 3)
self.assertEqual(result, 5)
2. Use Built-in Assertions
The unittest.TestCase class provides many assertion methods. Common ones include:
assertEqual(a, b)– check equalityassertTrue(x)/assertFalse(x)– check booleanassertRaises(Error, func, args)– check expected exceptions
Choose the right assertion to make your test intention clear.
3. Run Your Tests
Execute your test file from the command line:
python -m unittest test_calculator.py
Or add this at the bottom of your test file to run it directly:
if __name__ == '__main__':
unittest.main()
4. Organize and Improve
Keep tests small and independent. Use setUp() to prepare common objects and tearDown() to clean up. Name test files with a test_ prefix and group related tests in separate classes.
By following these steps, you’ll write maintainable unit tests that catch bugs early and serve as living documentation for your Python projects.