Comparing current time in unit test

I am currently writing a unit test that compares against strings. The first line is generated using a function. The other is hardcoded and serves as a link. My problem is that the function that creates the first row is putting the current time (time.Now ()) with seconds precision into the string. At the moment I am doing the same for reference, but it seems very ugly to me. My machine is fast enough for the test to pass, but I don't want to rely on that.

What are the general methods for conducting such tests?

+3


source to share


1 answer


You can stub type functions time.Now()

in your _test.go

files using a function init()

, 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

+1


source







All Articles