我正在测试是否有异常。
我有:
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.setStatus
。NEW_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/