15

在python中,我们如何为我们的类编写测试用例?例如:

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)

我知道有一种叫做单元测试的东西。但我完全不确定它是如何工作的。在网上找不到我理解的很好的解释。

4

2 回答 2

10

doctest是最简单的。测试写在docstring中,看起来像 REPL 剧集。

 ...

  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()
于 2012-05-10T00:22:11.410 回答
10

Hitchhiker's Guide to Python的“测试你的代码”部分讨论了 Python 中的一般测试实践/方法,以及以或多或少越来越复杂的顺序介绍特定工具。如前所述,doctest 是一种超级简单的开始方式……从那里开始,您可能希望转到 unittest() 及其他。

我的经验是 doctest 可以(并且应该)被用作一个快速而肮脏的测试,但要小心过度 - 它可能导致模块用户可能不想看的长而丑陋的文档字符串,特别是如果您的测试很详尽,并且包括各种极端情况。从长远来看,将这些测试移植到像 unittest() 这样的专用测试框架中是一种更好的做法。您可以在 doctest 中仅保留基础知识,以便查看文档字符串的任何人都可以快速了解该模块在实践中的工作方式。

于 2015-01-23T13:33:07.430 回答