Skip to content

Instantly share code, notes, and snippets.

@StevenACoffman
Created March 25, 2022 00:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save StevenACoffman/b98f7fbcf736a301b173717805b52376 to your computer and use it in GitHub Desktop.
Save StevenACoffman/b98f7fbcf736a301b173717805b52376 to your computer and use it in GitHub Desktop.
Time Tested techniques for testing time

You can use an unexported package variable pointing to the time.Now function.

var (
    timeNow   = time.Now
    timeAfter = time.After
)

// ...

type Obj struct{}
func (o Obj) TimeCriticalFunc(d time.Duration) bool {
    // Call timeAfter and timeNow.
}

And in your tests do

func TestTimeCriticalFunc(t *testing.T) {
    timeNow = func() time.Time {
        return myTime // Some time that you need
    }
    // "Redefine" timeAfter etc.
    if !Obj{}.TimeCriticalFunc(10 * 24 * time.Hour) {
        t.Fail()
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment