Module A includes import B at its top. However under test conditions I’d like to mock B in A (mock A.B) and completely refrain from importing B.
In fact, B isn’t installed in the test environment on purpose.
A is the unit under test. I have to import A with all its functionality. B is the module I need to mock. But how can I mock B within A and stop A from importing the real B, if the first thing A does is import B?
(The reason B isn’t installed is that I use pypy for quick testing and unfortunately B isn’t compatible with pypy yet.)
How could this be done?
You can assign to
sys.modules['B']before importingAto get what you want:test.py:
A.py:
Note B.py does not exist, but when running
test.pyno error is returned andprint(A.B.__name__)printsmock_B. You still have to create amock_B.pywhere you mockB‘s actual functions/variables/etc. Or you can just assign aMock()directly:test.py: