Stubbing Out time.Now() Globally: Exploring Alternatives
In testing code that depends on time-sensitive functionalities, the need arises to simulate time progression. While implementing a custom time interface can be an effective solution, its usage can become cumbersome due to the need to pass a variable around to track actual elapsed time.
Custom Time Package
As an alternative, consider creating a custom time package that wraps around the standard library's time package. This approach allows you to seamlessly switch between the real-time implementation and a mock implementation for testing. For example:
// custom_time.go package custom_time import ( "time" "sync" ) var ( mockTime time.Time mockMutex sync.Mutex ) func SetMockTime(t time.Time) { mockMutex.Lock() mockTime = t mockMutex.Unlock() } func ResetMockTime() { mockMutex.Lock() mockTime = time.Time{} mockMutex.Unlock() } func Now() time.Time { mockMutex.Lock() defer mockMutex.Unlock() if mockTime != (time.Time{}) { return mockTime } return time.Now() }
Advantages of Custom Package
Disadvantages of Custom Package
Caution Against System Clock Modification
It is strongly advised against modifying the system clock during tests to simulate time progression. This can lead to unpredictable consequences for other system components that rely on the accurate system time.
The above is the detailed content of How Can I Effectively Stub Out `time.Now()` Globally for Testing in Go?. For more information, please follow other related articles on the PHP Chinese website!