我今天开始进行单元测试,遇到一个问题,我觉得这很明显,但是也许你们会看到的。 该块是保存信息的文件
names.py
class Person:
def __init__(self, firstname, lastname, middlename = ""):
self.firstname = firstname
self.lastname = lastname
self.middlename = middlename
def fullname(self):
if self.middlename:
return self.firstname + " " + self.middlename + " " + self.lastname
else:
return self.firstname + " " + self.lastname
这是测试应用
import unittest
from names import Person
class TestName(unittest.TestCase):
def test_fullname(self):
rashka = Person("John","Smith","James")
self.assertEqual(rashka.fullname, "John James Smith")
if __name__ == "__main__":
unittest.main()
运行该错误消息
AssertionError: <bound method Person.fullname
of <names.Person object at 0x0371A690>> != 'John James Smith'
答案 0 :(得分:1)
您需要调用rashka.fullname()
,否则您正在将方法与str进行比较。
答案 1 :(得分:0)
正如其他答案所建议的,plainSum(1) _
是实例上的一种方法,因此需要像其他任何函数一样调用:
fullname
或者,您也可以考虑使用>>> rashka.fullname
<bound method Person.fullname of <names.Person object at 0x0371A690>>
>>> rashka.fullname()
'John James Smith'
装饰器来获取属性访问权限:
property
现在,class Person:
def __init__(self, firstname, lastname, middlename = ""):
self.firstname = firstname
self.lastname = lastname
self.middlename = middlename
@property # <-- new
def fullname(self):
if self.middlename:
return self.firstname + " " + self.middlename + " " + self.lastname
else:
return self.firstname + " " + self.lastname
将返回您在测试中编写的名称(不需要括号)。
rashka.fullname