在测试 golang 期间存根 time.Now()?

Stubbing time.Now() during tests golang?

我正在关注另一个答案:Is there an easy way to stub out time.Now() globally during test?

所以我有这个文件,我在其中做类似的事情:

var timeNow = time.Now

func GenerateTimestamp() int64 {
    now := timeNow() // current local time
    sec := now.Unix() // number of seconds since January 1, 1970 UTC

    return sec // int 64
}

我们在另一个函数中使用 GenerateTimestamp()

func AddTs() {
    // Some if check, use GenerateTimestamp() here
}

现在在我的测试文件上,我正在做类似的事情:

    now := time.Now()
    timeNow = func() int64 {
        // fmt.Println("looking for this", now.Unix())
        return now.Unix()
    }

我收到此错误 cannot use func literal (type func() int64) as type func() time.Time in assignment。我需要能够 return 一个 int64 类型(我的原始函数 returns),我该如何解决这个问题?

随时给我指点文档,我是 Go 新手!!

time.Now() is a function that returns a value of type time.Time:

func Now() Time

所以timeNow的类型是这个类型的函数:func() time.Time。这明显不同于func() int64.

您必须 return 一个 time.Time 值。如果你想 return 一个代表特定 unix 时间的 time.Time 值,你可以使用 time.Unix() 函数来获取该值,例如

unixsec := int64(1605139200) // This is 2020-11-12 00:00:00 +0000 UTC

timeNow = func() time.Time {
    return time.Unix(unixsec, 0)
}

如果你想return一个特定的date-time,你可以使用time.Date(),例如:

timeNow = func() time.Time {
    return time.Date(2020, 11, 12, 0, 0, 0, 0, time.UTC)
}

当然你不限于总是return同一时刻。您可以 return 在每次调用时递增时间值,例如:

unixsec := int64(1605139200) // This is 2020-11-12 00:00:00 +0000 UTC

timeNow = func() time.Time {
    unixsec++ // Increment number of seconds by 1
    return time.Unix(unixsec, 0)
}

timeNow 函数将 return 一个始终递增 1 秒的时间值(与上次调用 return 的值相比)。