In python, how do we write test cases for our classes? For example:
class Employee(object):
num_employees = 0
# numEmployess is incremented each time an employee is constructed
def __init__(self, salary=0.0, firstName="", lastName="", ssID="", DOB=datetime.fromordinal(1), startDate=datetime.today()): #Employee attributes
self.salary=salary
self.firstName = firstName
self.lastName = lastName
self.ssID = ssID
self.DOB = DOB
self.startDate = startDate
Employee.num_employees += 1 #keep this
def __str__(self): #returns the attributes of employee for print
return str(self.salary) + ', ' + self.firstName + ' ' + self.lastName + ', ' + self.ssID + ', ' + str(self.DOB) + ', ' + str(self.startDate)
I know there is something called unit testing. But I'm not sure how it works at all. Could not find a good explanation I understood online.
First you need to create a test file. Then import the unittest module, define the testing class that inherits from unittest. TestCase, and lastly, write a series of methods to test all the cases of your function's behavior. First, you need to import a unittest and the function you want to test, formatted_name() .
Unit testing is a method for testing software that looks at the smallest testable pieces of code, called units, which are tested for correct operation. By doing unit testing, we can verify that each part of the code, including helper functions that may not be exposed to the user, works correctly and as intended.
doctest
is the simplest. Tests are written in the docstring, and look like REPL episodes.
...
def __str__(self):
"""Returns the attributes of the employee for printing
>>> import datetime
>>> e = Employee(10, 'Bob', 'Quux', '123', startDate=datetime.datetime(2009, 1, 1))
>>> print str(e)
10, Bob Quux, 123, 0001-01-01 00:00:00, 2009-01-01 00:00:00
"""
return (str(self.salary) + ', ' +
self.firstName + ' ' +
self.lastName + ', ' +
self.ssID + ', ' +
str(self.DOB) + ', ' +
str(self.startDate)
)
if __name__ == '__main__':
import doctest
doctest.testmod()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With