How to Write Unit Test in Python?

Unit tests are written in order to test a specific piece of code and make sure that the code is working the way we want. A unit test will verify that your code is working and that the code inputs and outputs are as intended.

Python has a built-in support for unit testing. The Python unittesting framework was originally inspired by JUnit and has a similar flavor to major unit testing frameworks in other languages. It supports automation of tests, sharing of configuration and stop code for tests, aggregation of tests in collections, and independence of tests with respect to the reporting framework.

The Python unittest framework supports the following important concepts in an object-oriented way:

  • test fixture - A test fixture is the preparation required for one or more tests, and all related cleaning actions. These can include, for example, creating temporary or proxy databases, directories, or starting a server process.
  • test case - A test case is a single test unit that verifies a specific response to a particular set of inputs. The unittest framework provides a core class, TestCase, which can be used for creating new test cases.
  • test suite - A test suite is used to group the tests that have to be run together. It is a collection of test cases, test suites or both.
  • test runner - A test runner is a component that manages tests and provides the result to the user. The runner can use a GUI, a text interface, or return a special value to indicate the test results.

Here is a simple program to test two functions:

import unittest

def sum(a, b):
    return a + b

def minus(a, b):
    return a - b

class CalculatorTestCase(unittest.TestCase):

    def setUp(self):
        print("setUp called")
        self.a = 104
        self.b = 240

    def test_sum(self):
        print("test sum called")
        result = sum(self.a, self.b)
        self.assertEqual(result, self.a+self.b)

    def test_minus(self):
        print("test minus called")
        result = minus(self.a, self.b)
        self.assertEqual(result, self.a-self.b)
    def tearDown(self):
        print("tearDown called")
        self.a = 0
        self.b = 0

if __name__ == "__main__":
setUp called
test minus called
tearDown called
.setUp called
test sum called
tearDown called
Ran 2 tests in 0.000s

The above example is explained below:

  • We started by creating a testcase class (CalculatorTestCase) by subclassing unittest.TestCase.
  • The two individual tests methods whose names start with the letters test informs the test runner about which methods represent tests.
  • The setUp() method is used to set up the test fixture and is executed before any test method is run.
  • The tearDown() method is used to clean up resources and is executed after every test method is run.
  • The assertEqual() function checks the two given values for equality.