【问题标题】:Mock the return value of a function derived from an input parameter模拟从输入参数派生的函数的返回值
【发布时间】:2021-11-27 00:15:59
【问题描述】:

我想模拟从输入参数 (a) 派生的函数的返回值。
这是我的代码的样子。

 def load_data(a, b, c):
     data_source = a.get_function(b, c)
     ...
     return r_1, r_2, r_3

这是我尝试过但没有奏效的方法。我找不到任何模拟此类函数返回的来源。

@classmethod
def setUpClass(cls):
    cls.a = A.create()
    cls.data_needed_return = read_file()

def test_function(self):
    mocked = mock.Mock()
    self.a.get_function.return_value = self.data_needed_return

    import python_file
    data_source = python_file.load_data(None, None, None)

有人可以帮忙吗?

【问题讨论】:

    标签: python python-unittest python-unittest.mock


    【解决方案1】:

    不确定我是否正确理解了您的问题,但您是否正在寻找类似以下的内容?

    
    from unittest.mock import Mock
    
    def load_data(a, b, c):
        data_source = a.get_function(b, c)
        return data_source
    
    a = Mock()
    a.get_function.return_value = "Some data"
    
    x = load_data(a, 2, 3)
    
    print(x)
    
    

    【讨论】:

    • 这是我正在寻找的东西。您的解决方案给出了 TypeError:object is not callable, 不确定它是否尝试在没有正确模拟的情况下调用该函数
    • 您的代码运行良好!这是我需要从头到尾弄清楚的事情。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-24
    • 1970-01-01
    • 1970-01-01
    • 2015-10-21
    • 2021-10-26
    • 1970-01-01
    相关资源
    最近更新 更多