Search⌘ K
AI Features

Unit Testing With unittest

Explore how to write and run unit tests in Python using the unittest library. Understand the structure of test cases, methods for assertions, and best practices for keeping tests independent and concise. This lesson guides you in designing reliable tests that help maintain code quality and supports continuous integration.

Coding example

Let’s start our exploration with Python’s built-in test library. This library provides a common object-oriented interface for unit tests. The Python library for this is called, unsurprisingly, unittest. It provides several tools for creating and running unit tests, the most important being the TestCase class. (The names follow a Java naming style, so many of the method names don’t look very Pythonic.) The TestCase class provides a set of methods that allow us to compare values, set up tests, and clean up when they have finished.

Successful test execution

When we want to write a set of unit tests for a specific task, we create a subclass of TestCase and write individual methods to do the actual testing. These ...