Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

comparing current time in unit test

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?

like image 805
Gilrich Avatar asked Sep 10 '25 15:09

Gilrich


1 Answers

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

like image 172
Martin Gallagher Avatar answered Sep 13 '25 07:09

Martin Gallagher