2013-11-01 28 views
4

我一直在尝试在另一个函数中模拟这个函数调用,但没有成功。我如何成功地嘲笑这个?如何模拟另一个函数内部的函数?

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

有两个问题与您的代码:

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 
+0

在您说“modb”的补丁中。那是什么? –

+1

我在我的示例代码中有这样的评论:“#asssume class_b的模块名称是modb”。在你的问题中,你只是说'path.to.a模块'。 –

相关问题