dongzouqie4220 2013-09-23 22:58
浏览 75
已采纳

有没有一种简单的方法可以在测试过程中全局分配time.Now()?

Part of our code is time sensitive and we need to able to reserve something and then release it in 30-60 seconds etc, which we can just do a time.Sleep(60 * time.Second)

I have just implemented time interface and during test use a stubbed implementation of the time interface, similar to this golang-nuts discussion.

However, time.Now() is called in multiple sites which means we need to pass a variable around to keep track of how much time we have actually slept.

I was wondering if there is an alternative way to stub out time.Now() globally. Maybe making a system call to change the system clock?

Maybe we can write our own time package which basically wraps around the time package but allows us to change it?

Our current implementation works well, I am a go beginner and I am curious to see if anyone has other ideas?

  • 写回答

5条回答 默认 最新

  • dp6319 2013-09-23 23:07
    关注

    With implementing a custom interface you are already on the right way. I take it you use the following advise from the golang nuts thread you've posted:


    type Clock interface {
      Now() time.Time
      After(d time.Duration) <-chan time.Time
    }
    

    and provide a concrete implementation

    type realClock struct{}
    func (realClock) Now() time.Time { return time.Now() }
    func (realClock) After(d time.Duration) <-chan time.Time { return time.After(d) }
    

    and a testing implementation.


    Original

    Changing the system time while making tests (or in general) is a bad idea. You don't know what depends on the system time while executing tests and you don't want to find out the hard way by spending days of debugging into that. Just don't do it.

    There is also no way to shadow the time package globally and doing that would not do anything more you couldn't do with the interface solution. You can write your own time package which uses the standard library and provides a function to switch to a mock time library for testing if it is the time object you need to pass around with the interface solution that is bothering you.

    The best way to design and test your code would probably be to make as much code stateless as possible. Split your functionality in testable, stateless parts. Testing these components separately is much easier then. Also, less side effects means that it is much easier to make the code run concurrently.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题