In the code, I'm using the python method time()
:
from time import time
# Some code
t=time()
# Some more code
main.py
In my tests, I want to stub the time method with mockito, to return always the same value:
import time
#...
when(time).time().thenReturn(2)
#...
test.py
However, that doesn't work unless I change how I call the time method in main:
import time
t=time.time()
main_2.py
I would like to avoid changing the main code, or at least understand why that change is needed in order for the stub to work.
You are mocking the wrong module. Your code is using the name time
in its own namespace, not the name in the time
module, although both refer to the same function.
If test.py
is importing main.py
with import main
, then use
when(main).time().thenReturn(2)