I have several structs with fields of type time.Time
. I'm wondering what's the best practice to test them? Should I simply set the time.Time
fields to nil and test the rest of the struct (i.e. reflect.DeepEqual)? Otherwise is there a way make the time deterministic? Given the function below how would you test it?
type mystruct struct {
s string
time time.Time
}
// myfunc receives a string and returns a struct of type mystruct
// with the same string and the current time.
func myfunc(s string) mystruct {
return mystruct{s: s, time: time.Now()}
}
In case you need create a fake for time.Now() you can create TimeProvider and use it for getting real time.Now() or fake it.
This is very simple example
package main
import (
"fmt"
"time"
)
type TimeProvider interface {
Now() time.Time
}
type MyTimeProvider struct{}
func (m *MyTimeProvider) Now() time.Time {
return time.Now()
}
type FakeTimeProvider struct {
internalTime time.Time
}
func (f *FakeTimeProvider) Now() time.Time {
return f.internalTime
}
func (f *FakeTimeProvider) SetTime(t time.Time) {
f.internalTime = t
}
func main() {
var t MyTimeProvider
f := FakeTimeProvider{t.Now()}
fmt.Println(t.Now())
fmt.Println(f.Now())
}