Stubbing Time.Now() in golang
Some time it's really hard to test functionality that involves with system time. Especially when we wanted to test specific functionality. For example testing whether today is end of month. It's unrealistic to run this test case once every month.
If you are coming from ruby land, you might familiar with some test library that solve this problem like timecop. Actually it's not that hard to do it in Go also. There is couple of approach you can use.
First approach is passing the
time.Time object to every function.
This way you can either pass
time.Now() in your main pacakge
or call it with something like
time.Date(t.Year(), t.Month(), 1, 0, 0, 0, 0, time.UTC) in your test.
This work well but it's a bit cumbersome to pas it evertime we call the function
Another approach you can use, is to create a function to generate current time. And during the test you can change the implementation of the function. Here is how i do it (and a bonus function to generate begining of month and end of month)
now in your test you could do something like this:
now to the process that, it will see that currently it's 15 December 2000 8:00 UTC
Site related post: