您需要使用MagicMock而不是Mock来使__next__这样的魔术方法默认可用:
>>> from unittest import mock
>>> mock_coroutine = mock.MagicMock()
>>> mock_coroutine.__next__()
>>> mock_coroutine.__next__.assert_called_with()
Mock allows you to assign functions (or other Mock instances) to magic methods and they will be called appropriately. The MagicMock class is just a Mock variant that has all of the magic methods pre-created for you (well, all the useful ones anyway).
因此,或者,您仍然可以使用常规的Mock对象,但是随后您需要显式添加该属性:
>>> mock_coroutine = mock.Mock()
>>> mock_coroutine.__next__ = mock.Mock()
>>> mock_coroutine.__next__()
这是因为尽管Mock在您访问属性时即刻创建属性,但是带有前划线和后划线的任何属性都明确地免于此.参见this footnote:
The only exceptions are magic methods and attributes (those that have leading and trailing double underscores). Mock doesn’t create these but instead raises an AttributeError. This is because the interpreter will often implicitly request these methods, and gets very confused to get a new Mock object when it expects a magic method. If you need magic method support see 07002.
但是请注意,魔术方法通常是要在类而不是实例上查找的,因此直接将__next__属性添加到Mock实例仍然会失败. MagicMock类将为您解决此特定问题.