Testing

Stubbing Time.Now() in golang

Ahmy Yulrizka

Sometimes it’s really hard to test functionality that involve with system time. Especially when we want to test the function with a specific time. For example testing whether today is end of month or test 2 different behavior at a different time

Below we look into different ways we can mock or stub the time. Each with it’s own advantages and disadvantages.

Passing the time instance

 1func CheckEndOfMonth(now time.Time) {
 2    // business process
 3}
 4
 5func main() {
 6	CheckEndOfMonth(time.Now())
 7}
 8
 9// for test
10func TestCheckEndOfMonth(t *testing.T) {
11	CheckEndOfMonth(time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC))
12}