我正在测试是否有异常。
我有:

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']

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

谢谢

最佳答案

self.assertRaises需要一个函数,后跟任意数量的参数:在这种情况下,只需mro.setStatusNEW_STATUS将其参数汇编到self.assertRaises块内的函数调用mro.setStatus(NEW_STATUS)中,从而在发生时捕获并记录try...except
ValueError作为参数传递给mro.setStatus(NEW_STATUS)会导致self.assertRaises发生在ValueError能够捕获它之前。
因此,解决方法是将括号改为逗号:

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

关于python - assertRaises的单元测试问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3304642/

10-12 18:49