How to Mock time.Now in Go Tests

Replace time.Now with a variable function to inject fixed times in Go tests.

Replace time.Now() with a variable holding a function, then assign a mock function in your test.

var now = time.Now

func MyFunc() time.Time {
    return now()
}

func TestMyFunc(t *testing.T) {
    fixedTime := time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC)
    now = func() time.Time { return fixedTime }
    defer func() { now = time.Now }()
    
    if got := MyFunc(); got != fixedTime {
        t.Errorf("got %v, want %v", got, fixedTime)
    }
}