代码之家  ›  专栏  ›  技术社区  ›  Tal Weiss

python unittest:如何在异常中测试参数?

  •  5
  • Tal Weiss  · 技术社区  · 16 年前

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

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

    我的代码引发了:

    raise UnrecognizedAirportError('From')
    

    这很有效。

    如何测试异常中的参数是否是我所期望的?

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

    我希望这足够清楚-提前谢谢!

    塔尔

    2 回复  |  直到 13 年前
        1
  •  11
  •   S.Lott    16 年前

    这样地。

    >>> 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" )
    
        2
  •  1
  •   Alex Martelli    16 年前

    assertRaises 有点简单,并且不允许您测试所引发异常的详细信息,因为它属于指定的类。对于更细粒度的异常测试,需要使用 try/except/else 阻止(您可以在 def assertDetailedRaises 方法将您添加到自己的UnitTest测试用例的泛型子类中,然后让您的测试用例都继承您的子类而不是UnitTest)。