Skip to content

Instantly share code, notes, and snippets.

@endorama
Last active March 15, 2022 14:01
Show Gist options
  • Save endorama/315c4e9a9279d4701d58c1fd39d82a61 to your computer and use it in GitHub Desktop.
Save endorama/315c4e9a9279d4701d58c1fd39d82a61 to your computer and use it in GitHub Desktop.
Golang time testing pattern
package str
func UnixTimestamp() int64 {
return time.Now().Unix()
}
type FragmentCreator struct {
slug string
// timeNowUnix is only used in testing to override getting the current timestamp
timestamp func() int64
}
func (f FragmentCreator) filename() string {
filename := fmt.Sprintf("%d-%s.yaml", f.timestamp(), f.slug)
return filename
}
package str
func TestFilename(t *testing.T) {
fc := FragmentCreator{
slug: "foobar",
timestamp: func() int64 { return 1647345675 },
}
expected := "1647345675-foobar.yaml"
got := fc.filename()
assert.Equal(t, expected, got)
}
package vr
type FragmentCreator struct {
slug string
}
var timeNowUnix = time.Now().Unix
func filename(fc FragmentCreator) string {
t := timeNowUnix()
filename := fmt.Sprintf("%d-%s.yaml", t, fc.slug)
return filename
}
package vr
func TestFilename(t *testing.T) {
fc := FragmentCreator{
slug: "foobar"
}
timeNowUnix = func() int64 {
return 1647345675
}
expected := "1647345675-foobar.yaml"
got := filename(fc)
assert.Equal(t, expected, got)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment