'class'对象没有属性'method'

时间:2016-05-27 23:47:38

标签: python unit-testing class testing

我收到错误“AttributeError:'Test Employee'对象没有属性'increment_salary'”。不知道为什么我收到这个错误,因为'increment_salary'是一个方法,而不是属性,我99%肯定我是正确创建的。我已经搜索了,我看到的唯一答案是检查压痕和空格的混合,所以我经历了三次检查每个缩进。这可能是错的,因为我不熟悉如何在这里复制代码,但我确信我在geany中做得很好。

import unittest

class Employee():
    """stores and updates info for each employee"""
    def __init__(self, first_name, last_name, salary):
        self.first_name = first_name
        self.last_name = last_name
        self.salary = salary
    def update_salary(self, new_salary):
        self.salary = new_salary
    def increment_salary(self, increase):
        self.salary += increase

class TestEmployee(unittest.TestCase):

    def setUp(self):
        first_name = 'first'
        last_name = 'last'
        pay_name = 100
        self.employee = Employee(first_name, last_name, pay)

    def test_update_salary(self):
        new_salary = 110
        self.employee.update_salary(self.new_salary)
        self.assertEqual(self.new_salary, self.update_salary)

    def test_raise(self):
        increase = 10
        self.employee.increment_salary(increase)
        self.assertEqual(110, self.increment_salary(increase))

unittest.main()

1 个答案:

答案 0 :(得分:2)

您尝试在increment_salary()测试用例上调用TestEmployee

self.assertEqual(110, self.increment_salary(increase))

您忘了在self.employee上调用它。以下内容不会抛出异常:

self.assertEqual(110, self.employee.increment_salary(increase))

断言失败,因为Employee.increment_salary()总是返回None。您想测试测试中salary属性的设置:

def test_raise(self):
    increase = 10
    self.employee.increment_salary(increase)
    self.assertEqual(110, self.employee.salary)

请注意,方法也只是属性;它们是可调用的属性。