apitest
Mocks

Call counts

Control how many calls a mock answers, and find mocks that were never called.

By default a mock answers one call. A second matching call skips it and moves on to the next mock, and fails if there is none.

Times and AnyTimes

// must be called exactly twice
getUser := apitest.NewMock().
	Get("http://users/api/user/1234").
	RespondWith().
	Status(http.StatusOK).
	Times(2).
	End()

// may be called any number of times, including none
healthCheck := apitest.NewMock().
	Get("http://users/health").
	RespondWith().
	Status(http.StatusOK).
	AnyTimes().
	End()

apitest.New().
	Mocks(getUser, healthCheck).
	Handler(handler).
	Get("/").
	Expect(t).
	Status(http.StatusOK).
	End()
MethodBehaviour
Times(n)Answers n calls, and fails the test if fewer are made. A further call does not match.
AnyTimes()Answers any number of calls, including none. It takes precedence over Times.

A mock without Times that is never called does not fail the test. It is reported as unmatched instead.

Unmatched mocks

End() returns a result whose UnmatchedMocks method lists the mocks that no request matched:

getUser := apitest.NewMock().
	Get("http://users/api/user/1234").
	RespondWith().
	Status(http.StatusOK).
	Body(`{"id": "1234", "name": "jon"}`).
	End()

getPreferences := apitest.NewMock().
	Get("http://preferences/api/preferences/1234").
	RespondWith().
	Status(http.StatusOK).
	Body(`{"is_contactable": true}`).
	End()

audit := apitest.NewMock().
	Post("http://audit/api/events").
	RespondWith().
	Status(http.StatusAccepted).
	End()

result := apitest.New().
	Mocks(getUser, getPreferences, audit).
	Handler(handler).
	Get("/user/1234").
	Expect(t).
	Status(http.StatusOK).
	End()

for _, unused := range result.UnmatchedMocks() {
	t.Logf("mock was not called: %s", unused.URL.String())
}

An unused mock often means the test sets up a dependency the code no longer calls. Logging them, as above, keeps mock setup honest without making every test strict. To make a call mandatory, use Times(1).

On this page