英文:
comparing current time in unit test
问题
我目前正在编写一个单元测试,比较两个字符串。第一个字符串是使用一个函数生成的,而另一个字符串是硬编码的,作为参考。我的问题是,创建第一个字符串的函数将当前时间(time.Now())以秒为精度注入到字符串中。目前我对参考字符串也做同样的处理,但我觉得这样很丑陋。我的机器运行得足够快,所以测试通过了,但我不想依赖于这一点。
有哪些常用的技术可以进行这样的测试?
英文:
I'm currently writing a unit test that compares to strings. The first string is generated using a function. The other one is hard coded and serves as reference. My problem is, that the function creating the first string injects the current time (time.Now()) with precision in seconds into the string. At the moment I do the same for the reference but this seems very ugly to me. My machine runs fast enough so that the test passes but I don't want to rely on that.
What are general techniques to do such tests?
答案1
得分: 6
你可以在 _test.go
文件中使用 init()
函数来模拟 time.Now()
这样的函数,从而得到确定性的时间值:
package main
import (
"fmt"
"time"
)
var timeNow = time.Now
func main() {
fmt.Println(timeNow())
}
func init() {
// 取消注释并添加到 _test.go 的 init() 函数中
// timeNow = func() time.Time {
// t, _ := time.Parse("2006-01-02 15:04:05", "2017-01-20 01:02:03")
// return t
// }
}
参考链接:https://play.golang.org/p/hI6MrQGyDA
英文:
You can stub functions like time.Now()
in your _test.go
files, via the init()
function, this will give deterministic time values:
package main
import (
"fmt"
"time"
)
var timeNow = time.Now
func main() {
fmt.Println(timeNow())
}
func init() {
// Uncomment and add to _test.go init()
// timeNow = func() time.Time {
// t, _ := time.Parse("2006-01-02 15:04:05", "2017-01-20 01:02:03")
// return t
// }
}
答案2
得分: 0
我们可以使用Go包"github.com/tkuchiki/faketime"来模拟时间.Now()。
package main
import (
"fmt"
"github.com/tkuchiki/faketime"
"time"
)
func main() {
fmt.Println("伪造前的当前时间:", time.Now().UTC())
f := faketime.NewFaketime(2021, time.March, 01, 01, 01, 01, 0, time.UTC)
defer f.Undo()
f.Do()
fmt.Println("伪造后的当前时间:", time.Now())
}
以上代码的输出为:
伪造前的当前时间:2009-11-10 23:00:00 +0000 UTC
伪造后的当前时间:2021-03-01 01:01:01 +0000 UTC
可以在这里查看示例代码:go-playground示例
英文:
we can stub time.Now() by using go package "github.com/tkuchiki/faketime".
package main
import (
"fmt"
"github.com/tkuchiki/faketime"
"time"
)
func main() {
fmt.Println("Current Time Before Faking : ", time.Now().UTC())
f := faketime.NewFaketime(2021, time.March, 01, 01, 01, 01, 0, time.UTC)
defer f.Undo()
f.Do()
fmt.Println("Current Time After Faking : ", time.Now())
}
Output from the above code is :
Current Time Before Faking : 2009-11-10 23:00:00 +0000 UTC
Current Time After Faking : 2021-03-01 01:01:01 +0000 UTC
checkout the sample code : go-playground sample
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论