assertRaises的单元测试问题

时间:2010-07-21 23:18:54

标签: python unit-testing

我正在尝试测试异常。

我有:

def test_set_catch_status_exception(self):
    mro = self.mro
    NEW_STATUS = 'No such status'
    self.assertRaises(ValueError,mro.setStatus(NEW_STATUS))

我收到以下错误:

======================================================================
ERROR: test_set_catch_status_exception (__main__.TestManagementReviewGoalGetters)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test_ManagementReviewObjective.py", line 68, in test_set_catch_status_exception
    self.assertRaises(ValueError,mro.setStatus(NEW_STATUS))
  File "/Users/eric/Dropbox/ManagementReview.py", line 277, in setStatus
    raise ValueError('%s is not in the list of allowed statuses: %s' % (status,LIST_OF_STATUSES))
ValueError: No such status is not in the list of allowed statuses: ['Concern or Delay', 'On Track', 'Off Track/Needs Attention']

----------------------------------------------------------------------

由于

2 个答案:

答案 0 :(得分:37)

self.assertRaises需要一个函数mro.setStatus,后跟任意数量的参数:在本例中,只是NEW_STATUSself.assertRaises将其参数汇总到mro.setStatus(NEW_STATUS)块内的函数调用try...except中,从而捕获并记录ValueError(如果它发生)。

mro.setStatus(NEW_STATUS)作为参数传递给self.assertRaises会导致ValueErrorself.assertRaises陷阱之前发生。

所以解决方法是将括号更改为逗号:

self.assertRaises(ValueError,mro.setStatus,NEW_STATUS)

答案 1 :(得分:1)

请注意,如果您使用的是factory boy,则此程序包不允许将异常提升到肯定会失败的断言级别