【问题标题】:How to give different return values for a mocked function in pytest?如何为pytest中的模拟函数提供不同的返回值?
【发布时间】:2020-08-11 06:29:41
【问题描述】:

这里是要测试的函数:

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_firstoutput_second 有所不同,即在模拟时,它们应该在函数 func_to_be_tested 的同一测试调用中具有不同的 func1 返回值。

有什么办法吗?

谢谢

【问题讨论】:

    标签: python python-3.x unit-testing mocking pytest


    【解决方案1】:

    尝试以生成随机值或依赖于函数参数的值的方式定义函数。

    【讨论】:

      【解决方案2】:

      这就是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

      【讨论】:

      • 非常感谢@Mrbean Bremen!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-06
      • 2019-06-15
      • 1970-01-01
      • 1970-01-01
      • 2017-11-16
      • 1970-01-01
      • 2015-12-02
      相关资源
      最近更新 更多