I want to mock a class constructor in Python via mockito, i.e. return a Mock-class instance instead of the real one. Assuming you have an import statement in the form
from my.module import SomeClass
How can this be done? I've seen https://code-and-cocktails.herokuapp.com/blog/2015/01/19/mocking-class-constructor-in-python-with-mockito/ , which suggests
when(my.module).SomeClass().thenReturn(someFakeInstance)
however, this doesn't work with above's import statement for me; it only works when doing "import my.module" and instantiating via "my.module.SomeClass()".
Are there any viable solutions that work with the import statement above?
Thanks
What you tried is in general how it works, but since you do a deep import patching my.module is not want you want. You want to patch the module this code lives in. Say it is in a file module_under_test.py where you have
from x.y import SomeClass
Now, from the tests you look at it differently:
import module_under_test as mut
Now SomeClass is at mut.SomeClass, hence in the test you mock
when(mut).SomeClass(...)
This is super-confusing the first couple of times you're doing this, but not very special to mockito but how python works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With