Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- type Clock interface {
- Now() time.Time
- After(d time.Duration) <-chan time.Time
- }
- type realClock struct{}
- func (realClock) Now() time.Time { return time.Now() }
- func (realClock) After(d time.Duration) <-chan time.Time { return time.After(d) }
- 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 %sn", time.Now())
- }
- 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)
- package foo
- import "time"
- var Now = time.Now
- // The rest of your code...which calls Now() instead of time.Now()
- package foo
- import (
- "testing"
- "time"
- )
- var Now = func() time.Time { return ... }
- // Your tests
Add Comment
Please, Sign In to add comment