2013-11-01 22 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模塊'。 –

相關問題