Prerequisite: Object-Oriented Testing
Automated Object-Oriented Testing can be performed in Python using Pytest testing tool. In this article, we perform object-oriented testing by executing test cases for classes. We write a program that has one parent class called Product and three child classes – Snack, Beverage, and Staples. We implement all the classes and save them in a file called product.py. The classes have the following functions:
- Snack – printDetails() and getExpDate()
- Beverage – printDetails() and getExpDate()
- Staples – printDetails() and getExpDate()
It is important to note that getExpDate() is an overridden function in this case.
Code in product.py file:
name : cookies price : 60 shelf life : 6 months cookies will expire on 2020-04-03months super class Product name : rice price : 300 shelf life : 1 year rice will expire on 2021-01-23 name : coffee price : 250 shelf life : 2 years coffee will expire on 2020-12-17 done till here
To perform object-oriented testing, we write test cases for each of the classes. The following things should be kept in mind while writing these test cases:
- Create a separate test class for testing the functions of each class, for e.g. TestSnack, TestStaple, TestBeverage
- Write a test case for each function of a class
- Use assert keyword to add assertions in the test cases. The assert statement will return True if the test case passes or will return False if the test case fails
We have written test cases for each function present in all classes of product.py file except the Product class (parent class). This is because the Product class has just one function and that too has been overridden by the child classes, so writing a test case would make no difference. Therefore, we write 6 test cases in total where two test cases are written for each of the child classes.
Code in test_product.py file:
Note: The function name and the test file name should always start with the word ‘test‘.
To execute the above test cases, create two separate files, product.py and test_product.py in a single folder. To execute write the following command:
pytest -v shows the verbose output.
The output is shown below:
If we change the value in one of the assertion statements of a test case, it will lead the test case to fail. Refer to the output shown below:
In the output shown above, test_expDate() test case in class TestBeverage failed as the assertion statement resulted in a False expression.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course