Unit Testing With unittest

Learn about Python's unittest library to test the given code samples.

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 methods must all start with the name test. When this convention is followed, the tests automatically run as part of the test process. For simple examples, we can bundle the GIVEN, WHEN, and THEN concepts into the test method. Here’s a very simple example:

Get hands-on with 1200+ tech skills courses.