Mocking a method that is a dependancy is not working for me. When the method I need to test is calling its dependancy method, the real method is called instead of the mock version of it.
I do have the following files:
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..."
Finally the Unit Test:
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()
Perhaps it's important to mention that myLibrary.py and TestMyLibrary.py are in the same folder, but myOtherLibrary.py is under different folder level.
I hope you can help me find what I'm missing here.
Any suggestion will be very well appreciated. Thanks.