【问题标题】:Python unittest: how do I test the argument in an Exceptions?Python unittest:如何测试异常中的参数?
【发布时间】:2009-05-19 15:10:36
【问题描述】:

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

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

我的代码引发了:

raise UnrecognizedAirportError('From')

效果很好。

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

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

我希望这已经足够清楚了 - 在此先感谢!

塔尔。

【问题讨论】:

    标签: python unit-testing


    【解决方案1】:

    像这样。

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

    【讨论】:

    • 我知道不久前关于 python-dev 的一些讨论是关于修改 assertRaises 以返回捕获的异常(有人提到,twisted 和 bzr 都攻击了 unittest 来做到这一点)。有谁知道默认情况下实现它的任何框架。链接到 python-dev 注释:mail.python.org/pipermail/python-dev/2008-July/081293.html
    【解决方案2】:

    assertRaises 有点简单,除了属于指定类之外,不允许您测试引发异常的详细信息。对于更细粒度的异常测试,您需要使用try/except/else 块“滚动您自己的”(您可以在添加到您自己的unittest 测试用例的通用子类的def assertDetailedRaises 方法中一劳永逸地做到这一点,然后让你的测试用例都继承你的子类而不是单元测试的)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-07
      • 1970-01-01
      相关资源
      最近更新 更多