我是TDD新手。我已经创建了所有的主要功能(插入、搜索、删除等)。这是我的insert_beging()函数:def insert_beginning(self, node):
'''
Inserts a Node to the beginning of the list.
'''
node.set_next(self.head)
self.head = node
我的问题是,我的功能如何?我唯一能想到的办法是:
^{pr2}$
但是test_insert_beging()函数依赖于__str__() # string representation of my linked list
功能。我有一种感觉,我测试它的方式是不正确的(因为当我决定改变链表的表示方式时,我最终不得不重写我的测试用例)。有没有一种方法可以在不依赖我创建/自定义的另一个函数的情况下测试insert_beging()函数?在
编辑:对于那些想知道的人来说,目前我的链表的字符串表示只是用逗号分隔的节点的字符串表示。例如,具有节点1、2和“a”的链接列表将如下所示:1, 2, "a"
不过,我正计划更改链表的字符串表示形式(计划更改\uuustr\uuu()函数)。这是我意识到单元测试的方式可能不正确的时候。在
edit2(一条注释建议我创建一个函数来帮助我在链接列表中查找项目的索引):假设存在一个名为index_of(self,item)的函数,该函数将查找项目的索引。假设这是索引(self,item)的单元测试,并假设测试用例成功通过。在def test_index_of(self):
myList = LinkedList()
node1 = Node(1)
node2 = Node(2)
node3 = Node(3)
myList.head = node1
node1.next = node2
node2.next = node3
self.assertEqual(self.myList.index_of(1), 0)
self.assertEqual(self.myList.index_of(2), 1)
self.assertEqual(self.myList.index_of(3), 2)
现在,我可以依靠(self,item)函数的index_来确定insert_开头(self,node)是否正常工作?换句话说,如果test_insert_beging()函数是:class ListFunctionsTest(unittest.TestCase):
def setUp(self):
self.list1 = LinkedList()
self.node1 = Node(1)
def test_insert_beginning(self):
self.list1.insert_beginning(self.node1)
self.assertEqual(self.list1.index_of(1), 0)