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

前端 未结 7 1728
小鲜肉
小鲜肉 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:58

    I use the bouk/monkey package to replace the time.Now() calls in my code with a fake:

    package main
    
    import (
        "fmt"
        "time"
    
        "github.com/bouk/monkey"
    )
    
    func main() {
        wayback := time.Date(1974, time.May, 19, 1, 2, 3, 4, time.UTC)
        patch := monkey.Patch(time.Now, func() time.Time { return wayback })
        defer patch.Unpatch()
        fmt.Printf("It is now %s\n", time.Now())
    }
    

    This works well in tests to fake out system dependencies and avoids the abused DI pattern. Production code stays separate from test code and you gain useful control of system dependencies.

提交回复
热议问题