加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

如何在另一个函数内部模拟一个函数?

发布时间:2020-12-20 13:38:11 所属栏目:Python 来源:网络整理
导读:我一直试图在另一个函数中模拟这个函数调用但没有成功.我如何成功嘲笑这个? from mock import patchfrom 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 = fun
我一直试图在另一个函数中模拟这个函数调用但没有成功.我如何成功嘲笑这个?

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

解决方法

您的代码有两个问题:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读