Go Web Frameworks interview question · Most asked

How do you test HTTP handlers in Go?

Create a free account to save this page, take notes and track your progress. Sign in

Summary

Use net/http/httptest: build a request with httptest.NewRequest, a recorder with httptest.NewRecorder, call router.ServeHTTP(rec, req), and assert on status, headers and body, usually in table-driven tests with t.Run.

Longer Answer

Inject dependencies via interfaces so tests use fakes. Run with go test -race ./.... Keep a few integration tests against a real database (e.g. in a container). Fiber apps use app.Test(req) instead.

Key Points

  • httptest recorder, no server needed.
  • Table-driven subtests.
  • Interfaces + fakes; -race in CI.

Deep dive: Go Web Frameworks: Testing Go APIs

More most-asked Go Web Frameworks questions

← All Go Web Frameworks questions

Was this page helpful?