https://github.com/nitroshare/mocktime
Go package to simplify mocking time functions for deterministic testing
https://github.com/nitroshare/mocktime
Last synced: 8 months ago
JSON representation
Go package to simplify mocking time functions for deterministic testing
- Host: GitHub
- URL: https://github.com/nitroshare/mocktime
- Owner: nitroshare
- License: mit
- Created: 2025-07-27T19:45:25.000Z (10 months ago)
- Default Branch: main
- Last Pushed: 2025-08-10T23:28:55.000Z (9 months ago)
- Last Synced: 2025-08-11T01:12:27.524Z (9 months ago)
- Language: Go
- Size: 26.4 KB
- Stars: 0
- Watchers: 0
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE.txt
Awesome Lists containing this project
README
## mocktime
[](https://github.com/nitroshare/mocktime/actions/workflows/test.yml)
[](https://coveralls.io/github/nitroshare/mocktime?branch=main)
[](https://pkg.go.dev/github.com/nitroshare/mocktime)
[](https://opensource.org/licenses/MIT)
This package provides an easy way to mock specific functions in the `time` package:
```golang
import "github.com/nitroshare/mocktime"
// Same as time.Now()
mocktime.Now()
// Mock Now() and After()
mocktime.Mock()
defer mocktime.Unmock()
// All calls to Now() will return the same time...
mocktime.Now()
// ...until the time is advanced
mocktime.Advance(5 * time.Second)
// ...or explicitly set
mocktime.Set(time.Date(2025, time.May, 1, 0, 0, 0, 0, time.UTC))
// Calls to After() will block until the time is advanced (in another
// goroutine, for example)
<-mocktime.After(5 * time.Second)
// A drop-in replacement for time.Timer is provided:
t := mocktime.NewTimer(10 * time.Second)
<-t.C
t.Stop()
// ...as well as time.Ticker:
t := mocktime.NewTicker(1 * time.Second)
<-t.C
t.Reset(2 * time.Second)
t.Stop()
```
### Advanced Usage
A special utility function is provided that blocks until the next call to `After()`:
```golang
chanDone := make(chan any)
go func() {
// Normally, this will block until Set() or Advance() is called
<-mocktime.After(5 * time.Second)
close(chanDone)
}()
// Advance the time to the expiry of the After() call above; we don't need to
// worry if the goroutine has reached the After() call or not when this
// function is called as it will block until After() is called
mocktime.AdvanceToAfter()
// This read is guaranteed to succeed because the read on After() in the
// goroutine is unblocked
<-chanDone
```