在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)我知道有一种叫做单元测试的东西。但我根本不确定它是如何工作的。我在网上找不到一个好的解释。
发布于 2012-05-10 08:22:11
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()发布于 2015-01-23 21:33:07
"Testing Your Code" section of the Hitchhiker's Guide to Python讨论了Python语言中的一般测试实践/方法,以及以或多或少越来越复杂的顺序介绍特定工具。正如前面提到的,doctest是一种非常简单的测试方法,你可以使用start...and ()或者更多。
我的经验是,doctest可以(也应该)用作快速而肮脏的测试,但要注意不要走得太远-它可能会导致模块的用户可能不想看到又长又难看的docstring,特别是当您在测试中穷尽并包含所有类型的角例时。从长远来看,将这些测试移植到像unittest()这样的专用测试框架中是一个更好的实践。您可以在doctest中仅保留基础知识,以便任何查看文档字符串的人都能快速了解模块在实践中是如何工作的。
https://stackoverflow.com/questions/10525903
复制相似问题