Python unittest:如何测试异常中的参数?

6 投票
2 回答
2587 浏览
提问于 2025-04-15 11:42

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

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

然后我的代码抛出了:

raise UnrecognizedAirportError('From')

这个效果很好。

我想知道怎么测试异常中的参数是否是我预期的值?

我希望能以某种方式确认 capturedException.argument == 'From'

希望这样说得够清楚,提前谢谢你们!

Tal.

2 个回答

1

assertRaises 这个方法有点简单,只能检查抛出的异常是否属于某个特定的类别,无法测试异常的具体细节。如果你想更细致地测试异常,就需要自己动手写代码,使用 try/except/else 这种结构。你可以把这个过程封装成一个叫 def assertDetailedRaises 的方法,放在你自己创建的一个通用测试类中,然后让你的测试用例都继承这个类,而不是直接继承 unittest 的测试类。

11

像这样。

>>> 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" )

撰写回答