英文:
Does it make sense to test time-based fields ? (golang)
问题
我有几个结构体,其中的字段类型是 time.Time
。我想知道测试它们的最佳实践是什么?我应该简单地将 time.Time
字段设置为 nil,然后测试结构体的其余部分(例如使用 reflect.DeepEqual)吗?另外,有没有办法使时间确定性?
给定下面的函数,你会如何测试它?
type mystruct struct {
s string
time time.Time
}
// myfunc 接收一个字符串,并返回一个类型为 mystruct 的结构体,
// 其中包含相同的字符串和当前时间。
func myfunc(s string) mystruct {
return mystruct{s: s, time: time.Now()}
}
英文:
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()}
}
答案1
得分: 3
如果你需要为time.Now()创建一个假的时间,你可以创建一个TimeProvider并使用它来获取真实的time.Now()或者伪造它。
这是一个非常简单的例子:
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())
}
希望对你有帮助!
英文:
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())
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论