Test HTTP clients with httptest
Test HTTP clients with httptest
Inject a client and base URL into functions that call an HTTP API. httptest.NewServer supplies a real local HTTP server controlled by the test. This allows deterministic checks of requests, parsing and error handling without external APIs. NewTLSServer provides a TLS fixture and a client configured to trust its certificate.
package main
import ( "encoding/json" "errors" "fmt" "io" "net/http" "net/http/httptest" "time")
func check(err error) { if err != nil { panic(err) }}func fixture(h http.HandlerFunc) (*httptest.Server, *http.Client) { s := httptest.NewServer(h) c := s.Client() c.Timeout = 2 * time.Second return s, c}func fetchName(c *http.Client, u string) (string, error) { res, e := c.Get(u) if e != nil { return "", e } defer res.Body.Close() if res.StatusCode != 200 { return "", fmt.Errorf("status %d", res.StatusCode) } b, e := io.ReadAll(io.LimitReader(res.Body, 101)) if e != nil { return "", e } if len(b) > 100 { return "", errors.New("oversized") } var v struct { Name string `json:"name"` } if e = json.Unmarshal(b, &v); e != nil { return "", e } if v.Name == "" { return "", errors.New("missing name") } return v.Name, nil}func main() { s, c := fixture(func(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodGet || r.URL.Path != "/profile" { w.WriteHeader(400) return } w.Header().Set("Content-Type", "application/json") fmt.Fprint(w, `{"name":"Ada"}`) }) defer s.Close() name, e := fetchName(c, s.URL+"/profile") check(e) fmt.Println(name)}The fixture rejects a wrong method or path; the function verifies status, size, JSON syntax and nonempty name. This is a tiny API contract, not full schema validation. In Test functions use t.Fatal or t.Errorf instead of panic and printing. NewRecorder is useful for handlers, not for testing network clients end-to-end.
Expected output:
AdaTest malformed JSON over local TLS
package main
import ( "encoding/json" "errors" "fmt" "io" "net/http" "net/http/httptest" "time")
func fetchName(c *http.Client, u string) (string, error) { res, e := c.Get(u) if e != nil { return "", e } defer res.Body.Close() if res.StatusCode != 200 { return "", fmt.Errorf("status %d", res.StatusCode) } b, e := io.ReadAll(io.LimitReader(res.Body, 101)) if e != nil { return "", e } if len(b) > 100 { return "", errors.New("oversized") } var v struct { Name string `json:"name"` } if e = json.Unmarshal(b, &v); e != nil { return "", e } if v.Name == "" { return "", errors.New("missing name") } return v.Name, nil}func main() { s := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "not json") })) defer s.Close() c := s.Client() c.Timeout = 2 * time.Second _, e := fetchName(c, s.URL) var syntax *json.SyntaxError fmt.Println(errors.As(e, &syntax))}The test client verifies the fixture certificate, so this is a JSON parsing failure, not a trust failure. Do not copy fixture trust settings into production. Test good and malformed responses, missing required data, statuses and deadlines. Do not assert dynamic port numbers.
Expected output:
trueTry it locally
Use fetchName with valid JSON {"name":""}; print whether validation fails.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
HTTP clients 07: Test HTTP clients with httptest
Check the lesson objective before moving on.
Why inject the base URL?
What does NewRecorder alone not test?