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)
}
})
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?