Lesson 9: What is Unit Testing?
What is a Unit Test?
A unit test consists of instructions which are used to validate an application’s functionality. These instructions are called test cases.
The purpose of a unit test is to output the expected value of a piece of code. The application code outputs the actual value. Unit testing verifies that the expected values match the actual values.
To ensure that any incorrect output is found, NEVER copy the application code into the corresponding unit test.
Steps
To perform unit testing:
- Create a function called Testing() which consists of different test cases. This function returns output to the unit test for every test case. The Testing() function compares the difference between the expected value from the unit test and the actual value from the application code.
- Repeat step 1 for all the test data.
Example: Test a function you have created to compute the average of a list of numbers. The function Average() works as shown in the following image:
def Average(nums):
total = 0
for i in nums:
total += i
return total/lens(nums)
The Testing() function performs the Unit Testing. The function uses a library called Numpy to compare the results of the user-created function with the correct average of a given list, as shown in the following:
import numpy as np
def Testing():
test_cases = [[4,23,45,67,34],[3,4,6,2,3,4],[6,3,8,9,3]]
incorrect = 0
for k in range(len(test_cases)):
test = np.average(k)
CorrectAnswer = np.average(k)
if test != CorrectAnswer:
incorrect += 1
return incorrect
print("The number of failed test cases are", Testing())
Advantages of Unit Testing
- Improves the quality of code
- Speeds up the development of code
- Allows for defects to be found