断言一项行动引发了一场停止

时间:2014-12-16 01:29:41

标签: python unit-testing python-2.7 python-unittest

我有一个我想确认的生成器已经结束(在程序中的某一点。我在python 2.7中使用unittest

# it is a generator whould have only one item
item = it.next()
# any further next() calls should raise StopIteration
self.assertRaises(StopIteration, it.next())

但它失败并显示消息

======================================================================
ERROR: test_productspider_parse_method (__main__.TestMyMethods)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/myName/tests/__main__.py", line 94, in test_my_method
    self.assertRaises(StopIteration, it.next())
StopIteration

----------------------------------------------------------------------

1 个答案:

答案 0 :(得分:6)

您需要传递方法本身而不是调用方法。换句话说,放下括号。

self.assertRaises(StopIteration, it.next)

或者您可以将其用作上下文管理器:

with self.assertRaises(StopIteration):
    it.next()