Search⌘ K
AI Features

Unit Testing with unittest

Explore how to create automated unit tests in Python using the unittest framework. Learn to structure test cases, use assertions effectively, handle exceptions, and run test discovery to ensure your code works correctly and remains stable as it evolves.

Manual testing is slow, error-prone, and difficult to scale. As programs grow larger, fixing a bug in one area can easily introduce new bugs elsewhere, a problem known as a regression. To guard against this, we rely on automated tests. These tests run instantly, require no manual input, and verify that our code continues to behave as expected after every change.

In this lesson, we will use Python’s built-in unittest framework, an industry-standard tool for building reliable, repeatable test suites that act as a safety net throughout development.

The structure of a unit test

The unittest module is part of Python’s standard library. To use it, we organize our tests into classes that inherit from unittest.TestCase. This inheritance is important because it provides access to a rich set of assertion methods and signals to the test runner that the class contains tests.

One critical rule in unittest is its naming convention. Any method intended to be executed as a test must begin with the prefix test_. When the test runner executes, it scans each TestCase class, automatically discovers all methods whose names start with test_, and runs them one by one. If a method is named something like verify_logic instead of test_verify_logic, it will be silently ignored.

To see this process in action, we will first write a simple function called ...

Python
import unittest
def add_positive(a, b):
if a < 0 or b < 0:
return 0
return a + b
class TestMathOperations(unittest.TestCase):
def test_addition(self):
result = add_positive(5, 10)
self.assertEqual(result, 15)
def test_negative_input(self):
result = add_positive(-5, 10)
self.assertEqual(result, 0)
if __name__ == '__main__':
unittest.main()
...