[英]Unit Test Problem with assertRaises
我正在嘗試測試異常。
我有:
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
其參數匯編到try...except
塊內的函數調用mro.setStatus(NEW_STATUS)
,從而捕獲並記錄ValueError
如果它發生)。
將mro.setStatus(NEW_STATUS)
作為參數傳遞給self.assertRaises
會導致在self.assertRaises
捕獲它之前發生ValueError
。
所以解決方法是將括號更改為逗號:
self.assertRaises(ValueError,mro.setStatus,NEW_STATUS)
如果您正在使用factory boy
,請小心,此程序包不允許將異常提升到始終失敗的斷言級別
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.