I am mocking some objects in my unit tests using the python(3.6) unittest built-in library. Unfortunately I am facing some issues when mocking objects. For example I am writing a test for a function defined in a different file. This function creates a new instance of MyClass and I want to replaced that instance with a mock. So I use "patch".
#unit test file
....
@mock.patch('lib.mymodule.MyClass')
def test_myfunction(self, mock_myclass):
myfunction()
...
#Function file
from lib.mymodule import MyClass
....
def myfunction():
mc = MyClass
....
This does not work because when the test calls myfunction() it creates a real "MyClass" object and will not use the mock I tried to include using "patch".
However, if I use the class with its full path then the mock is used
import lib.mymodule
....
def myfunction():
mc = lib.mymodule.MyClass
...
To deal with the issue I have to get rid of this type of import: from ... import ... . Does anybody know another way to deal with the problem?
Thanks in advance