测试基于时间的字段是否有意义?(golang)

huangapple go评论111阅读模式
英文:

Does it make sense to test time-based fields ? (golang)

问题

我有几个结构体,其中的字段类型是 time.Time。我想知道测试它们的最佳实践是什么?我应该简单地将 time.Time 字段设置为 nil,然后测试结构体的其余部分(例如使用 reflect.DeepEqual)吗?另外,有没有办法使时间确定性?

给定下面的函数,你会如何测试它?

  1. type mystruct struct {
  2. s string
  3. time time.Time
  4. }
  5. // myfunc 接收一个字符串,并返回一个类型为 mystruct 的结构体,
  6. // 其中包含相同的字符串和当前时间。
  7. func myfunc(s string) mystruct {
  8. return mystruct{s: s, time: time.Now()}
  9. }
英文:

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?

  1. type mystruct struct {
  2. s string
  3. time time.Time
  4. }
  5. // myfunc receives a string and returns a struct of type mystruct
  6. // with the same string and the current time.
  7. func myfunc(s string) mystruct {
  8. return mystruct{s: s, time: time.Now()}
  9. }

答案1

得分: 3

如果你需要为time.Now()创建一个假的时间,你可以创建一个TimeProvider并使用它来获取真实的time.Now()或者伪造它。

这是一个非常简单的例子:

  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. type TimeProvider interface {
  7. Now() time.Time
  8. }
  9. type MyTimeProvider struct{}
  10. func (m *MyTimeProvider) Now() time.Time {
  11. return time.Now()
  12. }
  13. type FakeTimeProvider struct {
  14. internalTime time.Time
  15. }
  16. func (f *FakeTimeProvider) Now() time.Time {
  17. return f.internalTime
  18. }
  19. func (f *FakeTimeProvider) SetTime(t time.Time) {
  20. f.internalTime = t
  21. }
  22. func main() {
  23. var t MyTimeProvider
  24. f := FakeTimeProvider{t.Now()}
  25. fmt.Println(t.Now())
  26. fmt.Println(f.Now())
  27. }

希望对你有帮助!

英文:

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

  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. type TimeProvider interface {
  7. Now() time.Time
  8. }
  9. type MyTimeProvider struct{}
  10. func (m *MyTimeProvider) Now() time.Time {
  11. return time.Now()
  12. }
  13. type FakeTimeProvider struct {
  14. internalTime time.Time
  15. }
  16. func (f *FakeTimeProvider) Now() time.Time {
  17. return f.internalTime
  18. }
  19. func (f *FakeTimeProvider) SetTime(t time.Time) {
  20. f.internalTime = t
  21. }
  22. func main() {
  23. var t MyTimeProvider
  24. f := FakeTimeProvider{t.Now()}
  25. fmt.Println(t.Now())
  26. fmt.Println(f.Now())
  27. }

huangapple
  • 本文由 发表于 2014年12月17日 04:49:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/27513690.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定