[英]Python unittest: how do I test the argument in an Exceptions?
我正在使用unittest测试异常,例如:
self.assertRaises(UnrecognizedAirportError, func, arg1, arg2)
我的代码提出:
raise UnrecognizedAirportError('From')
哪个效果很好。
我如何测试异常中的参数是否符合我的预期?
我希望以某种方式断言capturedException.argument == 'From'
。
我希望这很清楚 - 提前感谢!
塔尔。
像这样。
>>> try:
... raise UnrecognizedAirportError("func","arg1","arg2")
... except UnrecognizedAirportError, e:
... print e.args
...
('func', 'arg1', 'arg2')
>>>
如果您只是将Exception
子类化,那么您的参数就在args
。
请参阅http://docs.python.org/library/exceptions.html#module-exceptions
如果异常类是从标准根类BaseException派生的,则关联的值将作为异常实例的args属性出现。
编辑更大的示例。
class TestSomeException( unittest.TestCase ):
def testRaiseWithArgs( self ):
try:
... Something that raises the exception ...
self.fail( "Didn't raise the exception" )
except UnrecognizedAirportError, e:
self.assertEquals( "func", e.args[0] )
self.assertEquals( "arg1", e.args[1] )
except Exception, e:
self.fail( "Raised the wrong exception" )
assertRaises
有点简单,并且不允许您测试属于指定类的凸起异常的细节。 对于异常的细粒度测试,您需要使用try/except/else
块“自己动手”(您可以在def assertDetailedRaises
方法中一次性完成这一操作,并将其添加到您自己的unittest测试用例的通用子类中,然后让你的测试用例都继承你的子类而不是unittest's)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.