Is there an easy way to stub out time.Now() globally during test?

前端 未结 7 1710
小鲜肉
小鲜肉 2020-12-05 06:43

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.Secon

7条回答
  •  粉色の甜心
    2020-12-05 06:53

    Also if you need to just stub time.Now you can inject dependency as a function, e.g.

    func moonPhase(now func() time.Time) {
      if now == nil {
        now = time.Now
      }
    
      // use now()...
    }
    
    // Then dependent code uses just
    moonPhase(nil)
    
    // And tests inject own version
    stubNow := func() time.Time { return time.Unix(1515151515, 0) }
    moonPhase(stubNow)
    

    Granted all that is a bit ugly if you come from dynamic languages background (e.g. Ruby) :(

提交回复
热议问题