创建一个单元测试

时间:2016-09-12 21:08:48

标签: python python-2.7

嘿,我是python的新手,我正在尝试为某些代码创建一个单元测试,我遇到了很多麻烦,说实话我想知道代码是否可以测试。

""" 
Core employee class
"""


class Employee(object):
empCount = 0

def __init__(self, name, salary, debt, takehome):
    self.name = name
    self.salary = salary
    self.debt = debt
    self.takehome = takehome

def display_employee(self):
    print "Name : ", self.name, ",Salary: ", self.salary, "Debt: ", \
        self.debt, "Take Home: ", self.takehome


emp1 = Employee("Scott", 2000, 200, 2000-200)

emp2 = Employee("Mary", 5000, 300, 5000-300)

emp3 = Employee("Sam", 4000, 700, 4000-700)

emp4 = Employee("Sarah", 7000, 2000, 7000-200)

emp5 = Employee("Charlie", 10000, 5000, 10000-5000)

emp6 = Employee("Tony", 16000, 20000, 16000-20000)


employees = [emp1, emp2, emp3, emp4, emp5, emp6]


for employee in employees:
    employee.display_employee()


Employee.empCount = len(employees)

print "Total Employees is %d" % Employee.empCount}

如果有人愿意帮助我,我会非常感激,如果我需要更改代码以便它可以更容易地对其进行单元测试

1 个答案:

答案 0 :(得分:0)

我认为你的班级是可以考试的。但是测试是微不足道的,因为你只有'_init__`方法和显示方法。

单元测试的开始是使用 unittest 库。

为每个“公共”方法编写一个测试函数:

class TestEmployee(unittest.TestCase):
    def test_init(self):
        ...

    def test_display_employee(self):
        ...

互联网上有很多教程,请看这个:Testing Your Code

另请参阅:Python testing