【问题标题】:How to mock a function inside of another function?如何在另一个函数中模拟一个函数?
【发布时间】:2013-11-01 00:58:01
【问题描述】:

我一直试图在另一个函数中模拟这个函数调用,但没有成功。我如何成功模拟这个?

from mock import patch
from path.to.a import function_a

@patch("class_b.function_c")
def test_method(self, method_to_mock):
    method_to_mock.return_value = 7890
    result = function_a() #error - type object 'class_b' has no attribute 'function_c'

#another module -- "path.to.a module"
def function_a():
    return class_b.function_c()

#another module
class class_b(class_c):
    pass

#another module
class class_c():
    @classmethod
    def function_c():
        return 123

【问题讨论】:

    标签: python unit-testing python-2.7 mocking


    【解决方案1】:

    您的代码有两个问题:

    1) 类方法声明不正确

    class class_c():
        @classmethod
        def function_c(cls):
            return 123
    

    2) @patch 使用不正确。您需要将其更改为

    def mock_method(cls):
        return 7890
    
    # asssume the module name of class_b is modb
    @patch("modb.class_b.function_c", new=classmethod(mock_method))
    def test_method():
        result = function_a() 
        print result # check the result
    

    【讨论】:

    • 在补丁中你说“modb”。那是什么?
    • 我的示例代码中有这样的注释:“# 假设 class_b 的模块名称是 modb”。在您的问题中,您刚刚说的是“path.to.a 模块”。
    猜你喜欢
    • 2019-04-19
    • 2018-08-13
    • 2020-02-15
    • 2021-04-19
    • 1970-01-01
    • 2018-01-21
    • 2017-06-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多