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