这是要测试的函数:
def func_to_be_tested():
output_first = func1()
output_second = func1()
.... rest of function
# func1 will be mocked while testing func_to_be_tested
我希望 output_first
和 output_second
不同,即在模拟时,它们应该在同一测试调用中具有不同的 func1
返回值函数func_to_be_tested
。
有什么办法可以做到这一点吗?
谢谢
最佳答案
这就是 side_effect
是为了.您可以为 side_effect
分配一个列表,列表中的每个值将用作后续调用的结果,例如:
from unittest import mock
from path_to_module import func_to_be_tested
@mock.patch('path_to_module.func1')
def test_func_to_be_tested(mocked_func1):
mocked_func1.side_effect = [output_first, output_second]
func_to_be_tested()
在这种情况下,func1
将在第一次调用中返回 output_first
,并在第二次调用中返回 output_second
。
关于python - 如何在 pytest 中为模拟函数提供不同的返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61463328/