Golang测试程序涉及时间

Pas*_* By 3 testing timer go

有一个对象依赖于正确运行的时间.不幸的是,定时持续时间本身太长而不能实时地对其进行实际测试,并且由于对象的性质,缩短持续时间会使测试的目的失败.

测试这样一个对象的最佳方法是什么?理想情况下,会有一些可以使用的任意快速运行的虚拟时钟.

type Obj struct{}
func (o Obj) TimeCriticalFunc(d time.Duration) bool {
    //do stuff
    //possibly calling multiple times time.Now() or other real time related functions
}

func TestTimeCriticalFunc(t *testing.T) {
    if !Obj{}.TimeCriticalFunc(10 * 24 * time.Hour) {
        t.Fail()
    }
}
Run Code Online (Sandbox Code Playgroud)

Ain*_*r-G 7

这实际上是在Andrew Gerrand的测试技术讲座中回答的.在你的代码中做

var (
    timeNow   = time.Now
    timeAfter = time.After
)

// ...

type Obj struct{}
func (o Obj) TimeCriticalFunc(d time.Duration) bool {
    // Call timeAfter and timeNow.
}
Run Code Online (Sandbox Code Playgroud)

并在你的测试中做

func TestTimeCriticalFunc(t *testing.T) {
    timeNow = func() time.Time {
        return myTime // Some time that you need
    }
    // "Redefine" timeAfter etc.
    if !Obj{}.TimeCriticalFunc(10 * 24 * time.Hour) {
        t.Fail()
    }
}
Run Code Online (Sandbox Code Playgroud)