2017-12-05 20 views
0

私が依存している方法を嘲笑していると、私にとって問題がありません。私がテストする必要のあるメソッドがその依存メソッドを呼び出すとき、実際のメソッドがモックバージョンの代わりに呼び出されます。Pythonで依存関係をmock.patchする方法は?

I行う必要があり、次のファイル:

myLibrary.py

from src.myOtherLibrary import myOtherLibrary 
class myLibrary(): 
    def __init__(): 
     self.myVar = myOtherLibrary() #dependancy 

    def my_method(): 
     method1 = self.method1() 

     externalMethod2 self.myVar.method2() #method2 called from the external class myOtherLibrary 

     return method1 + externalMethod2 

    def method1(): 
     return "method1 from myLibrary..." 

SRC最後に/ myOtherLibrary.py

class myOtherLibrary(): 
    def method2(): 
     return "method2 from myOtherLibrary..." 

ユニットテスト:

TestMyLibrary.py

import unittest 
import mock 
from myLibrary import myLibrary 
from src.myOtherLibrary import myOtherLibrary 
class TestMyLibrary(unittest.TestCase): 
    @mock.patch('myLibrary.myLibrary.method1') #mocking this works because it's a sibling method from my_method() to test 
    @mock.patch('src.myOtherLibrary.myOtherLibrary.method2') #this does not work because it's an external class from myLibrary 
    def test_my_method(my_method1_to_mock, my_method2_to_mock): 
     my_method1_to_mock.return_value = "something_to_return.." 
     my_method2_to_mock.return_value = "something_else_to_return.." 

     myLibraryVar = myLibrary() 
     result = myLibraryVar.my_method() 
     print result #I would expect to see this: "something_to_return..something_else_to_return.." 
        #But it actually prints this: "something_to_return..method2 from myOtherLibrary..." 
        #So mocking is not working for method2 

     self.assertEqual('something_to_return..something_else_to_return..', result) 

if __name__ == '__main__': 
    unittest.main() 

は、おそらくそれはmyLibrary.pyとTestMyLibrary.pyが同じフォルダ内にあることを言及することは重要だが、myOtherLibrary.pyは異なるフォルダレベルの下にあります。

私がここで紛失しているものを見つけるのを助けてくれることを願っています。

どのような提案も非常に高く評価されます。おかげさまで

答えて

0

モックしようとしているメソッドがクラスメソッドではないため、patchのようにすることはできません。したがって、patch.objectを使用する必要があります。

@mock.patch.object(myLibrary, 'method1') 
@mock.patch.object(myOtherLibrary, 'method2') 
... 
関連する問題