2012-03-07 73 views
9

我收到了一個我想單元測試的生成器對象。它經歷一個循環,並且在循環結束時某個變量仍然爲0,我引發一個異常。我想單元測試,但我不知道如何。 拿這個案例生成:如何在生成器對象中使用unittest的self.assertRaise異常?

class Example(): 
    def generatorExample(self): 
     count = 0 
     for int in range(1,100): 
      count += 1 
      yield count 
     if count > 0: 
      raise RuntimeError, 'an example error that will always happen' 

我想這樣做是

class testExample(unittest.TestCase): 
    def test_generatorExample(self): 
     self.assertRaises(RuntimeError, Example.generatorExample) 

然而,一臺發電機的對象不是calable,這給

TypeError: 'generator' object is not callable 

那麼,你如何測試一個生成器函數中是否引發異常?

回答

23

assertRaises是因爲Python 2.7上下文管理器,所以你可以做這樣的:

class testExample(unittest.TestCase): 

    def test_generatorExample(self): 
     with self.assertRaises(RuntimeError): 
      list(Example().generatorExample()) 

如果你有Python的< 2.7,那麼你可以使用lambda用盡發電機:

self.assertRaises(RuntimeError, lambda: list(Example().generatorExample())) 
+0

謝謝,但我必須在2.6,如果這是可能的。 – 2012-03-07 10:46:59

+0

我剛剛更新了我的答案,並以Python <2.7爲例說明了這一點。 – 2012-03-07 10:47:42

+0

非常感謝! – 2012-03-07 15:53:57