gpt4 book ai didi

Python...测试类?

转载 作者:太空狗 更新时间:2023-10-29 17:45:02 26 4
gpt4 key购买 nike

在 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)

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

最佳答案

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

关于Python...测试类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10525903/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com