Created
December 18, 2013 19:25
-
-
Save kylelemons/8028232 to your computer and use it in GitHub Desktop.
Example of how to stub out time.Now
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.