【问题标题】:Stub python time method with mockito (when)带有 mockito 的存根 python 时间方法(何时)
【发布时间】:2017-12-24 14:24:37
【问题描述】:

在代码中,我使用的是python方法time()

from time import time

# Some code
t=time()
# Some more code

main.py

在我的测试中,我想用 mockito 存根 time 方法,以始终返回相同的值:

import time
#...
when(time).time().thenReturn(2)
#...

test.py

但是,除非我更改在 main 中调用 time 方法的方式,否则这不起作用:

import time
t=time.time()

main_2.py

我想避免更改主代码,或者至少了解为什么需要进行更改才能使存根工作。

【问题讨论】:

    标签: python unit-testing testing mockito stub


    【解决方案1】:

    您在嘲笑错误的模块。您的代码在其 自己的 命名空间中使用名称 time,而不是 time 模块中的名称,尽管两者都引用相同的函数。

    如果test.pymain.pyimport main 一起导入,则使用

    when(main).time().thenReturn(2)
    

    【讨论】:

      猜你喜欢
      • 2016-01-12
      • 2018-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多