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

前端 未结 7 1721
小鲜肉
小鲜肉 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 07:10

    If the methods you need to mock are few, such as Now(), you can make a package variable which can be overwritten by tests:

    package foo
    
    import "time"
    
    var Now = time.Now
    
    // The rest of your code...which calls Now() instead of time.Now()
    

    then in your test file:

    package foo
    
    import (
        "testing"
        "time"
    )
    
    var Now = func() time.Time { return ... }
    
    // Your tests
    

提交回复
热议问题