Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python mockito - how to mock instance creation

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

like image 754
Bogey Avatar asked Feb 16 '26 20:02

Bogey


1 Answers

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.

like image 126
herr.kaste Avatar answered Feb 19 '26 09:02

herr.kaste



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!