Python Unit Testing

Unit Testing

What is unit testing?

Unit testing simply verifies that individual units of code (mostly functions) work as expected. Usually you write the test cases yourself, but some can be automatically generated.

The unit testing should be done as often as possible. The most obvious benefit is knowing down the road that when a change is made, no other individual units of code were affected by it if they all pass the tests.

Example of testing Student class

Here I’m going to make a very simple example to show how it works.

First, build the Student class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Student():
def __init__(self, name, score):
self.name = name
self.score = score
self.grade = None

def to_grade(self):
if self.score >= 60:
self.grade = 'Pass'
else:
self.grade = 'Fail'

def get_grade(self):
if self.grade:
return self.grade
else:
self.to_grade()
return self.grade

Then, build the unit testing script:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import unittest
from Student import Student


class TestStudent(unittest.TestCase):
def test_above_60(self):
s1 = Student('bart', 60)
self.assertEqual(s1.get_grade(), 'Pass')

def test_below_60(self):
s1 = Student('bart', 50)
self.assertEqual(s1.get_grade(), 'Fail')

def test_invalid(self):
pass


if __name__ == "__main__":
unittest.main()

Execution

Execute the script to make testing:

1
python test_student.py

to make the outut more verbose, add the -v into the command.

1
python test_student.py -v

Reference

  1. blog of liaoxuefeng: https://www.liaoxuefeng.com/wiki/1016959663602400/1017604210683936
  2. doc of Python 3.8: https://docs.python.org/3/library/unittest.html