[英]Unit Test Problem with assertRaises
I am trying to test for an exception. 我正在尝试测试异常。
I have: 我有:
def test_set_catch_status_exception(self):
mro = self.mro
NEW_STATUS = 'No such status'
self.assertRaises(ValueError,mro.setStatus(NEW_STATUS))
I get the following error: 我收到以下错误:
======================================================================
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']
----------------------------------------------------------------------
Thanks 谢谢
self.assertRaises
expects a function mro.setStatus
, followed by an arbitrary number of arguments: in this case, just NEW_STATUS
. self.assertRaises
需要一个函数mro.setStatus
,后跟任意数量的参数:在本例中,只是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. self.assertRaises
其参数汇编到try...except
块内的函数调用mro.setStatus(NEW_STATUS)
,从而捕获并记录ValueError
如果它发生)。
Passing mro.setStatus(NEW_STATUS)
as an argument to self.assertRaises
causes the ValueError
to occur before self.assertRaises
can trap it. 将
mro.setStatus(NEW_STATUS)
作为参数传递给self.assertRaises
会导致在self.assertRaises
捕获它之前发生ValueError
。
So the fix is to change the parentheses to a comma: 所以解决方法是将括号更改为逗号:
self.assertRaises(ValueError,mro.setStatus,NEW_STATUS)
如果您正在使用factory boy
,请小心,此程序包不允许将异常提升到始终失败的断言级别
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.