Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 39 ยท Testing and Deployment

Testing Gin Handlers

Test Gin routes without starting a server: build the router in a function, call ServeHTTP with httptest, assert status and JSON, table-driven tests, auth headers.

One of Gin's best features is how easy it is to test. A Gin engine is an http.Handler, so you can call it directly with a fake request and a recording response writer. No port, no network, no browser: a test takes microseconds, and it exercises your real routing, middleware, binding and JSON output.

Gin and the testing package are not available in the in-page runner, so the real test files here are read-only. The runnable examples build the same router shape with net/http and run the checks from main, printing PASS/FAIL lines like a test would. The technique (httptest.NewRequest, httptest.NewRecorder, ServeHTTP) is identical.

Design for testability

The one rule that makes everything else easy: build the router in a function instead of inside main.

Go
// router.go
func SetupRouter(store Store) *gin.Engine {
	gin.SetMode(gin.TestMode) // quiet logs; also set in tests
	r := gin.New()
	r.Use(gin.Recovery())

	r.GET("/ping", func(c *gin.Context) { c.String(http.StatusOK, "pong") })

	api := r.Group("/api")
	api.GET("/todos", listTodos(store))
	api.POST("/todos", createTodo(store))
	return r
}

// main.go
func main() { SetupRouter(NewDBStore()).Run(":8080") }

Handlers receive their dependencies (here a Store interface) as arguments or through a struct, instead of reading package-level globals. Then a test can pass a fake in-memory store. See Project Structure for how to organize this.

Your first test

A Gin test file ends in _test.go, lives next to the code, and uses httptest:

Go
func TestPing(t *testing.T) {
	r := SetupRouter(NewMemoryStore())

	w := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodGet, "/ping", nil)
	r.ServeHTTP(w, req)

	if w.Code != http.StatusOK {
		t.Fatalf("status = %d, want 200", w.Code)
	}
	if w.Body.String() != "pong" {
		t.Errorf("body = %q, want pong", w.Body.String())
	}
}

Run it with go test ./.... The recorder w collects the status (w.Code), headers (w.Header()) and body (w.Body) that the handler wrote.

Go Test a router without a server

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The first line, //go:debug httpmuxgo121=0, is needed only because this single-file runner has no go.mod; it switches on the method patterns ("GET /ping") of Go's modern ServeMux. In a normal module you omit it. Change Code == http.StatusCreated to another value to see a FAIL line with details. Writing the failure message so it shows the actual value is the habit that makes failing tests quick to debug.

Asserting JSON

Comparing raw strings is brittle because key order and spacing may change. Decode the body and compare values, or use the testify package.

Go
import (
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func TestCreateTodo(t *testing.T) {
	r := SetupRouter(NewMemoryStore())

	body := strings.NewReader(`{"title":"Ship it"}`)
	req := httptest.NewRequest(http.MethodPost, "/api/todos", body)
	req.Header.Set("Content-Type", "application/json")
	w := httptest.NewRecorder()
	r.ServeHTTP(w, req)

	require.Equal(t, http.StatusCreated, w.Code)

	var got Todo
	require.NoError(t, json.Unmarshal(w.Body.Bytes(), &got))
	assert.Equal(t, "Ship it", got.Title)
	assert.False(t, got.Done)
	assert.NotZero(t, got.ID)
}

require stops the test on failure (like t.Fatal); assert records the failure and continues. Always set Content-Type: application/json on test requests that send JSON, or ShouldBindJSON may reject them.

Table-driven tests

Go's idiom for many cases of one behaviour is a table of inputs and expectations, each run as a subtest with t.Run. It is perfect for validation rules and status codes.

Go
func TestCreateTodoValidation(t *testing.T) {
	r := SetupRouter(NewMemoryStore())

	tests := []struct {
		name   string
		body   string
		status int
	}{
		{"valid", `{"title":"Buy milk"}`, http.StatusCreated},
		{"missing title", `{}`, http.StatusBadRequest},
		{"blank title", `{"title":"   "}`, http.StatusBadRequest},
		{"too long", `{"title":"` + strings.Repeat("a", 300) + `"}`, http.StatusBadRequest},
		{"broken json", `{"title":`, http.StatusBadRequest},
	}
	for _, tc := range tests {
		t.Run(tc.name, func(t *testing.T) {
			req := httptest.NewRequest(http.MethodPost, "/api/todos", strings.NewReader(tc.body))
			req.Header.Set("Content-Type", "application/json")
			w := httptest.NewRecorder()
			r.ServeHTTP(w, req)
			if w.Code != tc.status {
				t.Errorf("status = %d, want %d (body %s)", w.Code, tc.status, w.Body)
			}
		})
	}
}
Go A table-driven check of validation rules

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Testing authenticated routes

Protected routes need a credential. Create a valid token in the test, or have a helper that signs one with the same test secret your app uses (see JWT Authentication), and set the header like a real client.

Go
func authedRequest(method, path, token string, body io.Reader) *http.Request {
	req := httptest.NewRequest(method, path, body)
	req.Header.Set("Authorization", "Bearer "+token)
	req.Header.Set("Content-Type", "application/json")
	return req
}

func TestProfileRequiresToken(t *testing.T) {
	r := SetupRouter(NewMemoryStore())

	w := httptest.NewRecorder()
	r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/api/me", nil))
	assert.Equal(t, http.StatusUnauthorized, w.Code)

	w = httptest.NewRecorder()
	r.ServeHTTP(w, authedRequest(http.MethodGet, "/api/me", makeTestToken(t, 42), nil))
	assert.Equal(t, http.StatusOK, w.Code)
}

Always test both sides: the rejected request and the accepted one. A middleware that rejects everything also passes the first half.

What to test, and what to leave alone

  • Do test: status codes, JSON shape, validation failures, auth and permission rules, and error mapping (a missing record gives 404, not 500).
  • Test middleware in isolation with a tiny router that has just that middleware and one handler.
  • Keep tests independent. Create a fresh router and store per test; never rely on order.
  • Use go test -race to catch data races in handlers that touch shared state, and -cover to see what is untested.
  • Do not test Gin itself. Trust that routing works; test the rules you wrote.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why can a Gin engine be tested without starting a server?

    A handler plus httptest.NewRecorder is all you need; no sockets are involved.
  2. 2. What is the main benefit of a SetupRouter function?

    Separating router construction from main means tests reuse the real routes without running main.
  3. 3. What does require.Equal do differently from assert.Equal?

    require calls t.FailNow, so later lines that depend on the check do not run.
  4. 4. Why test a protected route both with and without a token?

    You need to prove that valid credentials are accepted as well as invalid ones rejected.

Summary

  • Build the router in a function that takes its dependencies; call r.ServeHTTP(w, req) with httptest.
  • Check status, headers and decoded JSON, not raw strings.
  • Use table-driven subtests for validation rules and status codes.
  • Test authentication from both sides, run with -race, and keep each test independent.

Next: Testing with Databases and Fakes