A wrapper around Go's time package to ease testing.
The sole purpose of this package is to provide a way to test code, using gomock, that uses time functions from Go's time package. While there are ways to get around (e.g. make durations for tickers configurable, so we can override during tests, etc.), it's always better to have more control over time functions like tickers (when the next tick happens), timers (when the timer expires), etc.
NOTE Only the following functions are available:
Now()
NewTicker()
NewTimer()
Sleep()
After()
AfterFunc()
Tick()
// mypackage.go
package mypackage
import (
"fmt"
"github.com/transcelestial/clock"
)
func MyFunc(c clock.Clock) string {
return c.Now().Format(time.RFC3339)
}
// mypackage_test.go
package mypackage
import (
"testing"
"github.com/transcelestial/clock"
"github.com/stretchr/testify/assert"
"github.com/transcelestial/clock/mockclock"
)
func TestMyFunc(t *testing.T) {
ctrl := gomock.NewController(t)
// create a mock Clock
c := mockclock.NewMockClock(ctrl)
// set some expectations
now := time.Date(2018, 12, 31, 0, 0, 0, 0, time.UTC)
c.EXPECT().
Now().
Return(now)
assert.Equal(t, "2018-12-31T00:00:00Z", MyFunc(c))
}
See example_clock_test and example_mockclock_test for more examples.
You may also want to try out these alternatives:
If you wish to contribute, please use the following guidelines:
- Use conventional commits
- Use effective Go