在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)
我知道有些东西叫做单元测试。但我一点也不确定它是怎么工作的。在网上找不到一个我能理解的好解释。
"Testing Your Code" section of the Hitchhiker's Guide to Python讨论了Python中的一般测试实践/方法,并以或多或少越来越复杂的顺序介绍了特定的工具。如前所述,doctest是一种超级简单的开始方式……从这里开始,您可能希望转到unittest()和更高版本。
我的经验是,doctest可以(也应该)作为一个快速而肮脏的测试使用,但是要注意不要过分——它可能会导致长而难看的docstring,而您的模块的用户可能不想看到,特别是如果您在测试中非常详尽,并且包含了各种各样的角落案例。从长远来看,将这些测试移植到像unittest()这样的专用测试框架中是一种更好的做法。您可以在doctest中只留下基础知识,以便任何查看docstring的人都能快速了解模块在实践中的工作方式。
^{} 是最简单的。测试是在docstring中编写的,看起来像REPL集。
相关问题 更多 >
编程相关推荐