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)
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?