在代码中,我使用了 python 方法 time()
:
from time import time
# Some code
t=time()
# Some more code
main.py
在我的测试中,我想用 mockito stub time 方法,以始终返回相同的值:
import time
#...
when(time).time().thenReturn(2)
#...
测试.py
但是,除非我更改在 main 中调用时间方法的方式,否则这不起作用:
import time
t=time.time()
main_2.py
我想避免更改主要代码,或者至少了解为什么需要进行更改才能使 stub 正常工作。
最佳答案
您在模拟错误的模块。您的代码在其自己的 命名空间中使用名称 time
,而不是在 time
模块中使用名称,尽管两者都引用相同的函数。
如果 test.py
正在使用 import main
导入 main.py
,则使用
when(main).time().thenReturn(2)
关于python - stub python 时间方法与 mockito (when),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45188445/