Python Unit Testing - Python Programming by Example (2015)

Python Programming by Example (2015)

18. Python Unit Testing

This chapter explains how to build unit testing in Python.

18.1 Getting Started

Unit testing is a software development process in which the smallest testable parts of an application, called units, are individually and independently scrutinized for proper operation. Unit testing can be used to minimize bugs on the application.

In Python, we can use unittest framework, . Please read it to obtain more information.

18.2 Demo

For testing, we create a class and do unit testing for this class.

Write a file, called and write these scripts.

class Mathu:

def __init__(self):

print('call __init__ from Mathu class')

def add(self, num_a, num_b):

return num_a + num_b

def div(self, num_a, num_b):


result = num_a / num_b

except ZeroDivisionError as e:

raise e

return result

def check_even(self, number):

return number % 2 == 0

Now we want to test this class by the following scenario:

· testing add()

· testin div()

· testing check_even()

· testing for exception error

You can write these scripts.

import unittest

import mathu

class TestMathu(unittest.TestCase):

def test_add(self):

res = mathu.Mathu().add(5, 8)

self.assertEqual(res, 13)

def test_div(self):

res = mathu.Mathu().div(10, 8)

self.assertGreater(res, 1)

def test_check_even(self):

res = mathu.Mathu().check_even(4)


def test_error(self):

self.assertRaises(ZeroDivisionError, lambda:mathu.Mathu().div(5, 0))

if __name__ == '__main__':


Save into a file, called

Now you can run the program.

$ python3

Program output: