Unit Testing

You’ll learn about the concept of unit testing in Python in this lesson.

Introduction and structure of unit testing

A unit test tests the methods in a single class. A test case tests the response of a single method to a particular set of inputs.

To do unit testing, you have to do the following:

  • import unittest
  • import fileToBeTested or from fileToBeTested import *

    Reminder: If you use from file import * you don’t have to precede every function call with the name of the file it was imported from.

  • Write a class SomeName(unittest.TestCase). Within the class:
    • Define methods setUp(self) and tearDown(self), if desired. These are both optional.
    • Provide one or more testSomething(self) methods. You may include other methods, but the names of test methods must begin with test.
  • At the end of the test file, put unittest.main().

Role each component of unit testing play

Here’s what the unittest.main() does. For each and every method whose name begins with test, the unittest.main method calls setUp() if you have provided one. Then, it calls the test method and the tearDown() method if you have provided one. So, every test is sandwiched between setUp and tearDown.

The purpose of the setUp method is to make sure everything is in a known, pristine state before calling the test method. This way, you can make sure that the results of running one test do not affect the results of a later test.

The purpose of tearDown is to remove artifacts (such as files) that may ...