Python...testing classes?

python, testing

Solution

`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()

Problem

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.

Original source