assertRaises 的单元测试问题 [英] 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
将其参数组装到 mro.setStatus(NEW_STATUS)
块内的函数调用 try...except
中,从而捕获和记录ValueError
如果发生.
self.assertRaises
expects a function mro.setStatus
, followed by an arbitrary number of arguments: in this case, just NEW_STATUS
. self.assertRaises
assembles its arguments into the function call mro.setStatus(NEW_STATUS)
inside a try...except
block, thus catching and recording the ValueError
if it occurs.
将 mro.setStatus(NEW_STATUS)
作为参数传递给 self.assertRaises
会导致 ValueError
在 self.assertRaises 之前发生
可以捕获它.
Passing mro.setStatus(NEW_STATUS)
as an argument to self.assertRaises
causes the ValueError
to occur before self.assertRaises
can trap it.
所以解决方法是将括号更改为逗号:
So the fix is to change the parentheses to a comma:
self.assertRaises(ValueError,mro.setStatus,NEW_STATUS)
这篇关于assertRaises 的单元测试问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!