go-clock

A library for mocking time in Golang

MIT License

Stars
5

Clock

A library for mocking time in Golang.

Prerequisites

  • Go >= 1.17

Install

go get go.nhat.io/clock

Usage

Real 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())

Static clock

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)),
	}
}

Mock

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.
}

cucumber/godog

See godogx/clocksteps

Donation

If this project help you reduce time to develop, you can give me a cup of coffee :)

Paypal donation

       or scan this