我编写了一个单元测试来强制抛出异常。抛出异常,但我的单元测试语句由于某种原因没有捕获它,并且意外失败。
这是单元测试:
def test900_001_ShouldRaiseExceptionDuplicateID(self):
hist = projecthistory.ProjectHistory()
myProject = project.Project(id = 42, locR = 10, locP = 15, locA = 30, eP = 200, eA= 210)
hist.addProject(myProject)
myProject2 = project.Project(id = 42, locR = 15, locP = 25, locA = 40, eP = 300, eA = 410)
self.assertRaises(ValueError, projecthistory.ProjectHistory, hist.addProject(myProject2))
这是与此相关的代码:
def addProject(self, proj):
duplicate = False
checkId = proj.getId()
#check to see if that id is already in the container if so, raise ValueError
#append project to container
for project in self.theContainer:
if (project.getId() == checkId):
duplicate = True
break
if(duplicate == False):
self.theContainer.append(proj)
else:
raise ValueError("ProjectHistory.addProject: Duplicate ID found. Project not added to repository.")
return len(self.theContainer)
基本上,项目被添加到名为 theContainer 的列表中。但是,如果两个 ID 相同,则不会添加副本。通过在要添加的单元测试中强制添加两个具有相同 ID 的项目,会引发异常。
这是我得到的回溯:
Traceback (most recent call last):
File "C:\Users\blah\workspace\blahID\CA06\test\projecthistoryTest.py", line 46, in test900_001_ShouldRaiseExceptionDuplicateID
self.assertRaises(ValueError, projecthistory.ProjectHistory, hist.addProject(myProject2))
File "C:\Users\blah\workspace\blahID\CA06\prod\projecthistory.py", line 38, in addProject
raise ValueError("ProjectHistory.addProject: Duplicate ID found. Project not added to repository.")
ValueError: ProjectHistory.addProject: Duplicate ID found. Project not added to repository.
问题可能出在 assertRaises 中的第三个参数上吗?(hist.addProject(myProject2))