python - “类”对象没有属性 'method'

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

最佳答案

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

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)

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

关于python - “类”对象没有属性 'method',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37493789/

相关文章:

unit-testing - 在 Flask 单元 pytest 中模拟 current_app

java类的初始化顺序,它是如何工作的?

c# - 将类从 C#(AVL 树节点)转换为 C

python - 获取 Pandas df中连续值为零的列的索引

python - 带有自定义类实例的operator.index

unit-testing - 使用 Scala 从 SBT 获取堆栈跟踪

c# - 应该如何测试内部类和方法?

c++ - 从另一个方法调用非静态成员方法

python - 在 Python 和 C++ 中根据彩色图像计算的 pig 描述符的差异

python - 查找 cv2.findContours() 的面积(Python、OpenCV)