If side_effect is an iterable then each call to the mock will return
the next value from the iterable.
示例:
from unittest.mock import Mock
class Iterable:
def __iter__(self):
return self
Iterable.__next__ = Mock(side_effect=[1, 2, 3])
for i in Iterable():
print(i)
明白了。您只能通过一个模拟迭代器迭代一次,之后它将耗尽。要解决这个问题,请使用MagicMock及其迭代器,可以根据需要多次使用。在
您可以使用
Mock
的side_effect
参数来替代正在测试的类的__next__
属性。在根据documentation:
示例:
该输出:
^{pr2}$相关问题 更多 >
编程相关推荐