apitest

Introduction

apitest is a simple, extensible library for writing behavioural tests against Go HTTP services.

apitest tests a Go HTTP service the way its clients use it. You build a request, send it to the handler, and assert on the response. Calls the handler makes to other services can be answered by mocks, and every test can render a sequence diagram of what happened.

hello_test.go
func TestHello(t *testing.T) {
	apitest.New().
		HandlerFunc(helloHandler).
		Get("/hello").
		Query("name", "gopher").
		Expect(t).
		Status(http.StatusOK).
		Header("Content-Type", "application/json").
		Body(`{"message": "hello gopher"}`).
		End()
}

Why apitest

In a behavioural test the internal structure of the application is unknown to the test. Data goes in, and the outputs are expected to meet certain conditions. Tests written this way survive refactoring, document how the API behaves, and catch the bugs users would actually see.

apitest keeps those tests short:

  • Fluent builders describe the request and the expected response in one readable chain.
  • Any http.Handler works, including routers from chi, gin, echo and gorilla. A running server can be tested too.
  • Declarative mocks answer the outbound HTTP calls your handler makes, with matchers for every part of the request.
  • Sequence diagrams show each test's request, mocked calls, database queries and response.
  • No third party dependencies. apitest integrates with testing, Ginkgo and your own assertion libraries.

The API is stable. The library is maintained, issues are addressed and feature requests are considered.

Where to next

Every example on this site is tested

The code samples are included from a Go module that runs against the latest apitest release, so they compile and pass.

On this page