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
那麼,你如何測試一個生成器函數中是否引發異常?
謝謝,但我必須在2.6,如果這是可能的。 – 2012-03-07 10:46:59
我剛剛更新了我的答案,並以Python <2.7爲例說明了這一點。 – 2012-03-07 10:47:42
非常感謝! – 2012-03-07 15:53:57