2009-05-19 136 views
5

我的異常使用單元測試的測試,例如:Python單元測試:我如何測試異常中的參數?

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

和我的代碼提出:

raise UnrecognizedAirportError('From') 

效果很好。

如何測試異常中的參數是我所期望的呢?

我想以某種方式斷言capturedException.argument == 'From'

我希望這是足夠清晰的 - 在此先感謝!

Tal。

回答

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

+1,比我的清潔得多:) – 2009-05-19 15:21:44

1

assertRaises是一個有點簡單化,並且不會讓你測試引發的異常的細節超越它屬於一個特定的類別。爲了對異常進行更細粒度的測試,您需要使用try/except/else塊來「自行設計」(您可以通過將def assertDetailedRaises方法添加到您自己的unittest測試用例的通用子類中,然後進行測試案例都是繼承你的子類而不是unittest的)。