Python:assertRaises在单元测试中出错...异常未被捕获

时间:2013-04-16 19:15:54

标签: python unit-testing

我编写了一个单元测试来强制抛出异常。抛出异常,但我的单元测试语句由于某种原因没有捕获它,并且意外失败。

以下是单元测试:

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))

1 个答案:

答案 0 :(得分:6)

您的怀疑是正确的,问题在于对hist.addProject()的呼吁。

您写道:

self.assertRaises(ValueError, projecthistory.ProjectHistory,
    hist.addProject(myProject2))

ValueError加注。但它在

hist.addProject(myProject2)

追溯告诉你。因此,assertRaises永远不会被调用,因为在调用之前会引发异常。

考虑它的方法是assertRaises只能捕获实际设法被调用的异常。如果准备其参数的行为引发异常,则assertRaises甚至不会运行,因此无法捕获任何内容。

如果您希望调用addProject()中的异常只是更改您的断言:

self.assertRaises(ValueError, hist.addProject, myProject2)

或者您可以使用lambda推迟hist.addProject()的调用:

self.assertRaises(ValueError, 
    lambda: projecthistory.ProjectHistory(hist.addProject(myProject2)))