Python模拟对象迭代器不能多次迭代

2024-06-26 00:15:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用模拟迭代器功能来返回单元测试的迭代器。在我测试的代码中,I循环遍历对象多次,但它似乎不起作用,只在第一次运行。在

self.mock_scene.bpyscene.objects.__iter__ = mock.Mock(return_value=iter([mock_lamp_object, mock_lamp_object]))

Tags: 对象代码self功能returnobjectsobjectvalue
2条回答

明白了。您只能通过一个模拟迭代器迭代一次,之后它将耗尽。要解决这个问题,请使用MagicMock及其迭代器,可以根据需要多次使用。在

您可以使用Mockside_effect参数来替代正在测试的类的__next__属性。在

根据documentation

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)

该输出:

^{pr2}$

相关问题 更多 >