In the docs, it explains why patching at at the function definition level doesn't work:
Imagine we have a project that we want to test with the following structure:
a.py -> Defines SomeClass b.py -> from a import SomeClass -> some_function instantiates SomeClass
Now we want to test
some_function
but we want to mock outSomeClass
usingpatch()
. The problem is that when we import moduleb
, which we will have to do then it importsSomeClass
from modulea
. If we usepatch()
to mock outa.SomeClass
then it will have no effect on our test; moduleb
already has a reference to the realSomeClass
and it looks like our patching had no effect.
The core explanation is "module b
already has a reference to the real SomeClass
", but I don't fully understand the concept here. Can someone give me a deeper explanation?