0

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

1 Answer 1

1

I found the answer

The class needs to be patched regarding where it is being seen or used. In this case it will be:

@mock.patch('lib.module_with_function_file.MyClass')

The same applies when patching modules

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.