Python 单元测试中遇到 AttributeError: \’TestEmployee\’ object has no attribute \’employee\’,怎么办?
对于一个文章开发者来说,牢固扎实的基础是十分重要的,就来带大家一点点的掌握基础知识点。今天本篇文章带大家了解《Python 单元测试中遇到 AttributeError: \’TestEmployee\’ object has no attribute \’employee\’,怎么办?》,主要介绍了,希望对大家的知识积累有所帮助,快点收藏起来吧,否则需要时就找不到了!
python中的attributeerror问题
在使用python时,遇到了attributeerror异常,提示消息是”testemployee’ object has no attribute ’employee”。这是怎么回事?
问题分析
这个问题出现在单元测试代码中。在主代码中,实例化了一个名为 employee 的 employee 对象,并将它赋值给 self.employee 。但是,在测试方法 test_give_default_raise 中,出现了错误。
解决方案
要解决这个问题,需要检查 setup 方法是否写错了。在 python 单元测试中,setup 方法会在每个测试方法运行之前被调用,用来初始化测试环境。这里,把 setup 写成了 setup,导致 python 无法识别该方法。
修正后的 setup 方法写法如下:
def setUp(self): self.employee = Employee('taylor', 'swift', 20000)
修改后,setup 方法将正确实例化 employee 对象,并将其分配给 self.employee 。这将解决 attributeerror 异常,单元测试将能够正常运行。
今天关于《Python 单元测试中遇到 AttributeError: \’TestEmployee\’ object has no attribute \’employee\’,怎么办?》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注公众号!