Python unittest:如何在Exceptions中测试参数?

时间:2009-05-19 15:10:36

标签: python unit-testing

我正在使用unittest测试异常,例如:

self.assertRaises(UnrecognizedAirportError, func, arg1, arg2)

我的代码提出了:

raise UnrecognizedAirportError('From')

效果很好。

如何测试异常中的参数是否符合预期?

我希望以某种方式断言capturedException.argument == 'From'

我希望这很清楚 - 提前谢谢!

塔尔。

2 个答案:

答案 0 :(得分:11)

喜欢这个。

>>> try:
...     raise UnrecognizedAirportError("func","arg1","arg2")
... except UnrecognizedAirportError, e:
...     print e.args
...
('func', 'arg1', 'arg2')
>>>

如果您只是将args子类化,那么您的参数位于Exception中。

请参阅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" )

答案 1 :(得分:1)

assertRaises有点过分了,并且不允许您测试属于指定类的凸起异常的细节。对于异常的细粒度测试,您需要使用try/except/else块“自己动手”(您可以在def assertDetailedRaises方法中一次性地执行此操作,并将其添加到您自己的unittest的子类中测试用例,然后让你的测试用例都继承你的子类而不是unittest的。)

相关问题