问题是要修复故意不正确的代码,以便可以执行 pyUnit 测试。代码中的错误将通过测试发现,然后更正。我的最后一个测试在代码中产生了一个错误,但我无法发现它!
给定代码(带错误)
def linear( target, list ):
""" returns the position of target,
if not found returns -1"""
position = 0
if len(list)==0:
return -1
else:
while position <= (len(list)+1):
if target == list[position]:
return position
position += 1
return -1
和我的测试:
import unittest
# import the module(s) to be tested:
from LinearSearch import *
class TestLinearSearch(unittest.TestCase):
# setUp - run prior to the start of each test case
def setUp(self):
# initialize test fixtures
return
def test_smoke(self):
# very simple test to insure test framework is correct
self.assertTrue(1)
# additional test_xxx methods follow....
def test_emptyList(self):
self.assertEqual(linear(4,[]),-1)
def test_singleChar(self):
self.assertEqual(linear(1,[1]),0)
def test_isInList(self):
self.assertEqual(linear(4,[1,2,3,4,5]),3)
def test_isNotInList(self):
self.assertEqual(linear(8,[1,2,3,4,5]),-1)
if __name__ == '__main__':
unittest.main()
产生我的错误的测试是最后一个测试:“test_isNotInList(self)”,它是一个索引越界错误......应该很简单,但我只需要一点帮助。