How do I mock time in tests in Go?

In Go, mocking time in tests can be accomplished by using interfaces and dependency injection. By creating a time provider interface, you can substitute the real time function with a mock implementation during testing. This allows you to control the flow of time within your tests, making them more predictable and reliable.

Go, Go testing, mocking time, time manipulations in Go, dependency injection in Go

This article explains how to mock time in Go tests by using interfaces and provides a practical example to illustrate the concept.

package main

import (
    "fmt"
    "time"
)

type TimeProvider interface {
    Now() time.Time
}

type RealTimeProvider struct{}

func (r RealTimeProvider) Now() time.Time {
    return time.Now()
}

func DoSomething(t TimeProvider) {
    currentTime := t.Now()
    fmt.Println("Current time:", currentTime)
}

// In tests
type MockTimeProvider struct {
    mockTime time.Time
}

func (m MockTimeProvider) Now() time.Time {
    return m.mockTime
}

func Example() {
    mockTimeProvider := MockTimeProvider{mockTime: time.Date(2023, 10, 1, 10, 0, 0, 0, time.UTC)}
    DoSomething(mockTimeProvider)
}

Go Go testing mocking time time manipulations in Go dependency injection in Go