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

yay*_*ayu 3 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())
Run Code Online (Sandbox Code Playgroud)

但它失败了

======================================================================
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

----------------------------------------------------------------------
Run Code Online (Sandbox Code Playgroud)

fal*_*tru 6

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

self.assertRaises(StopIteration, it.next)
Run Code Online (Sandbox Code Playgroud)

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

with self.assertRaises(StopIteration):
    it.next()
Run Code Online (Sandbox Code Playgroud)