简体   繁体   中英

Python mockito - how to mock instance creation

I want to mock a class constructor in Python via mockito, ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM