A library for mocking time in Golang.
Go >= 1.17
go get go.nhat.io/clock
The clock will return time using time
package
package mypackage
import "go.nhat.io/clock"
type Application struct {
clock clock.Clock
}
func (a *Application) Do() {
ts := a.clock.Now()
// Other logic.
}
func New(clock clock.Clock) *Application {
return &Application{
clock: clock,
}
}
var app = New(clock.New())
The clock will return a fixed timestamp.
package mypackage
import (
"time"
"go.nhat.io/clock"
)
type Application struct {
clock clock.Clock
}
func (a *Application) Do() {
ts := a.clock.Now()
// ts is "2020-01-02T03:04:05Z"
// Other logic.
}
func New() *Application {
return &Application{
clock: clock.Fix(time.Date(2020, 1, 2, 3, 4, 5, 0, time.UTC)),
}
}
The clock is mocked using stretchr/testify/mock
package mypackage
import (
"testing"
"time"
clockMock "go.nhat.io/clock/mock"
)
func TestApplication(t *testing.T) {
t.Parallel()
ts := time.Date(2020, 1, 2, 3, 4, 5, 0, time.UTC)
clock := clockMock.Mock(func(c *mock.Clock) {
c.On("Now").Return(ts).Once()
})(t)
app := New(clock)
// assertions.
}
If this project help you reduce time to develop, you can give me a cup of coffee :)
or scan this