How do I write table-driven tests for handlers?

In Go, table-driven tests are a powerful way to test handlers and other functions systematically by providing different inputs and expected outputs in a structured format.

Go, table-driven tests, handlers, testing, web development

Learn how to implement table-driven tests for your HTTP handlers in Go to ensure reliable and maintainable code.

package main import ( "net/http" "net/http/httptest" "testing" ) func helloHandler(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Hello, World!")) } func TestHelloHandler(t *testing.T) { tests := []struct { name string requestPath string expectedStatus int expectedBody string }{ {"Valid Request", "/", http.StatusOK, "Hello, World!"}, {"Invalid Request", "/invalid", http.StatusNotFound, "404 page not found"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { req := httptest.NewRequest("GET", tt.requestPath, nil) w := httptest.NewRecorder() helloHandler(w, req) res := w.Result() if res.StatusCode != tt.expectedStatus { t.Errorf("expected status %d, got %d", tt.expectedStatus, res.StatusCode) } body := w.Body.String() if body != tt.expectedBody { t.Errorf("expected body '%s', got '%s'", tt.expectedBody, body) } }) } }

Go table-driven tests handlers testing web development