A Practical Guide to Writing Unit Tests in Python

Unit tests are essential for ensuring your Python code works as expected. They catch bugs early, make refactoring safer, and improve code quality. Python’s built-in unittest framework provides everything you need to write and run these tests efficiently.

To begin, create a Python file for your tests (e.g., test_utils.py) and import the unittest module. Then define a class that inherits from unittest.TestCase. Each test you write will be a method inside that class.

Article illustration

Writing Test Methods

Each test method must start with the word test. Inside, you set up input data, call the function you want to test, and use assertion methods provided by unittest to check the results.

  • assertEqual(a, b) – check that a and b are equal
  • assertTrue(x) – verify x is True
  • assertRaises(exception, func, *args) – confirm that a specific exception is raised

Example:

def test_addition(self):
    result = add(2, 3)
    self.assertEqual(result, 5)

Running Tests

Navigate to your project directory and run the test file with Python’s module flag:

python -m unittest test_utils.py

You can also use pytest (requires installation) for a more concise output and automatic test discovery.

Organizing Test Files

Place your test files in a separate tests/ directory. Use a descriptive file name like test_user_functions.py. Each module or class in your project should have a corresponding test file.

Writing unit tests may feel like extra work at first, but it pays off quickly. Start with small tests for individual functions, then build up to more complex scenarios. Your future self will thank you!

sarah antaboga
Author: sarah antaboga

Leave a Reply

Your email address will not be published. Required fields are marked *