duannao1920 2014-12-16 20:49
浏览 36

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

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条回答 默认 最新

  • dousuitang5239 2014-12-16 22:55
    关注

    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())
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题