How to Perform Unit Testing in Python?

Originally posted on kdnuggets.

Unit testing is an important part of the software development life cycle as it helps to ensure that code is correct and working as intended. This article aims to introduce the concept of unit testing in Python and provide a basic tutorial on how to write and run unit tests using a unittest module.


Verifying the code in isolation is necessary to ensure our code meets the quality standards and works as expected. While making a simple recipe, we taste it at various stages and adjust the flavors accordingly. Extending this concept to code, we constantly look through our code to validate its correctness. When it comes to testing, we can perform either manual testing or automated but manual testing is a tedious and time-consuming process. Automated testing involves the execution of the tests by a script instead of a human. There are various kinds of testing in automated testing like unit testing, integration testing, stress testing, etc but we will focus on unit testing for this tutorial.

Importance of Unit Testing

Unit testing is the technique in which individual units are analyzed for errors to make your code stable and future-proof. These units may be individual functions, a complete class, or an entire module. In most cases, these units have no dependencies on the other part of the code. It is important because these units are the basic building blocks of your application and if they are faulty then your application to break. It also enhances the developer’s productivity and encourages modular programming.


Many test runners are available for Python such as

  • Unittest
  • Pytest
  • Nose2
  • Testify
  • DocTest

For this tutorial, we will be using unittest which is the built-in testing framework in Python standard library. It contains both the testing framework and the test runner and offers a variety of features ranging from test automation and aggregating tests into collections to the independence of tests from reporting framework. It has the following requirements:

  • Each unit test can be created as a method extending the TestCase Class and prefix your method with a test to inform the test runner about the test methods
  • Using the sequence of special assertion methods that determine whether the test case has passed or failed. Some of the most commonly used assertion methods are mentioned below:
Method Description
.assertEqual(a, b) a == b
.assertNotEqual(a, b) a != b
.assertTrue(x) bool(x) is True
.assertFalse(x) bool(x) is False
.assertIs(a, b) a is b
.assertIs(a, b) a is not b
.assertIsNone(x) x is None
.assertIsNotNone(x) x is not None
.assertIn(a,b) a in b
.assertNotIn(a,b) a not in b
.assertIsInstance(a, b) isinstance(a, b)
.assertNotIsInstance(a, b) not isinstance(a, b)


Source: unittest official documentation

Steps to Perform Unit Testing using UnitTest

  • Write the code that you want to test in the Python File like
  • Create a new Python file for your unit tests starting with the keyword test like
  • Import the unittest module and
  • Create a class extending the class unittest.TestCase.
  • Write the test methods starting with the test keyword like test_functionName(self) and use assert methods to verify the behavior of the code being tested.
  • Run the command  python -m unittest in the terminal or invoke the main method of unittest in the test file and run python


Let’s create a file named that calculates the area of the rectangle.

def calc_rectangle_area(length, width):
    return length * width

Create a test file and write the following code:

import unittest
import calc

class TestRectangleArea(unittest.TestCase):
    def test_area_calculation(self):
        self.assertEqual(calc.calc_rectangle_area(2, 4), 8, "Incorrect area for a rectangle with length 2 and width 4")
        self.assertEqual(calc.calc_rectangle_area(3, 5), 15, "Incorrect area for a rectangle with length 3 and width 5")
        self.assertEqual(calc.calc_rectangle_area(10, 10), 100, "Incorrect area for a rectangle with length 10 and width 10")

if __name__ == '__main__':


Run python in your terminal. The following output will be displayed:

Ran 1 test in 0.001s



Now, change the formula of the calculating rectangle to verify our test cases.

def calc_rectangle_area(length, width):
     return length * width * 2


Again run python in your terminal.

self.assertEqual(calc.calc_rectangle_area(2, 4), 8, "Incorrect area for a rectangle with length 2 and width 4")
AssertionError: 16 != 8: Incorrect area for a rectangle with length 2 and width 4

Ran 1 test in 0.001s

FAILED (failures=1)

You can also extend this code to handle errors like division by zero.


While the unittest module provides us with the basic set of tools for writing and running unit tests, there are also third-party libraries offering more advanced features. Nonetheless, Unit testing remains an important part of the software development life cycle and can help you catch bugs early on resulting in more reliable and maintainable code. I hope you enjoyed reading the article. Please feel free to share your thoughts or feedback in the comment section.

Kanwal Mehreen is an aspiring software developer with a keen interest in data science and applications of AI in medicine. Kanwal was selected as the Google Generation Scholar 2022 for the APAC region. Kanwal loves to share technical knowledge by writing articles on trending topics, and is passionate about improving the representation of women in tech industry.
Source: kdnuggets