3

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?

Gilrich
  • 305
  • 3
  • 13
  • 1
    compare only the part of the string that doesn't contain the timestamp, if this is an option. – tivio Jun 20 '17 at 12:36
  • 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) may related to your question. – putu Jun 20 '17 at 13:44

2 Answers2

6

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

See: https://play.golang.org/p/hI6MrQGyDA

Martin Gallagher
  • 4,444
  • 2
  • 28
  • 26
  • This is exactly what I was looking for. Thank you. I didn't know that init() functions were possible. – Gilrich Jun 21 '17 at 06:09
0

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