Skip to content

Instantly share code, notes, and snippets.

@kylelemons
Created December 18, 2013 19:25
Show Gist options
  • Save kylelemons/8028232 to your computer and use it in GitHub Desktop.
Save kylelemons/8028232 to your computer and use it in GitHub Desktop.
Example of how to stub out time.Now
package foo
import "time"
// in your main package
var timeNow = time.Now
// in the _test.go:
func init() {
// Panic if any tests cause timeNow to be called without stubbing it out
timeNow = func() time.Time {
panic("now called without stub")
}
}
func TestFoo() {
// Restore to the panicky stub at the end of the test
defer func(orig func() time.Time) {
timeNow = orig
}(timeNow)
// We can now reassign timeNow to do whatever we want
timeNow = func() time.Time {
return time.Now().UTC()
}
timeNow()
// ... as many times as we want
timeNow = func() time.Time {
return time.Time{}
}
timeNow()
}
@iand
Copy link

iand commented Dec 18, 2013

This just gave me the insight I needed to tackle some tests in my current project where I am calling functions directly defined in another package. I just need to alias them with a func variable in my application and use the alias instead of the original function, then override it in the test.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment