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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With