2017-06-20 61 views
3

我目前正在編寫一個與字符串比較的單元測試。第一個字符串是使用函數生成的。另一個是硬編碼並作爲參考。我的問題是,創建第一個字符串的函數在字符串中以秒爲單位注入當前時間(time.Now())。目前我的參考文獻也一樣,但這對我來說似乎很難看。我的機器運行速度足夠快,以便測試通過,但我不想依賴於此。比較單元測試中的當前時間

做這些測試的一般技術是什麼?

+1

比較是沒有按」字符串的只有一部分t包含時間戳,如果這是一個選項。 – tivio

+1

[This https://stackoverflow.com/questions/18970265/is-there-an-easy-way-to-stub-out-time-now-globally-in-golang-during-test](https:// stackoverflow.com/questions/18970265/is-there-an-easy-way-to-stub-out-time-now-globally-in-golang-during-test)可能與您的問題有關。 – putu

回答

1

您可以存根功能,就像在你_test.go文件time.Now(),通過init()功能,這會給確定的時間值:

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 
    // } 
} 

參見:https://play.golang.org/p/hI6MrQGyDA

+0

這正是我一直在尋找的。謝謝。我不知道init()函數是可能的。 – Gilrich