package health import ( "encoding/json" "net/http" "net/http/httptest" "testing" ) func TestHealthHandler(t *testing.T) { tests := []struct { name string method string expectedStatus int expectedBody HealthResponse shouldHaveBody bool }{ { name: "GET request returns 200 OK with status ok", method: http.MethodGet, expectedStatus: http.StatusOK, expectedBody: HealthResponse{Status: "ok"}, shouldHaveBody: true, }, { name: "POST request returns 405 Method Not Allowed", method: http.MethodPost, expectedStatus: http.StatusMethodNotAllowed, shouldHaveBody: false, }, { name: "PUT request returns 405 Method Not Allowed", method: http.MethodPut, expectedStatus: http.StatusMethodNotAllowed, shouldHaveBody: false, }, { name: "DELETE request returns 405 Method Not Allowed", method: http.MethodDelete, expectedStatus: http.StatusMethodNotAllowed, shouldHaveBody: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { req, err := http.NewRequest(tt.method, "/health", nil) if err != nil { t.Fatal(err) } rr := httptest.NewRecorder() handler := http.HandlerFunc(HealthHandler) handler.ServeHTTP(rr, req) // Check status code if status := rr.Code; status != tt.expectedStatus { t.Errorf("handler returned wrong status code: got %v want %v", status, tt.expectedStatus) } if tt.shouldHaveBody { // Check content type expectedContentType := "application/json" if ct := rr.Header().Get("Content-Type"); ct != expectedContentType { t.Errorf("handler returned wrong content type: got %v want %v", ct, expectedContentType) } // Check response body var response HealthResponse if err := json.NewDecoder(rr.Body).Decode(&response); err != nil { t.Errorf("failed to decode response body: %v", err) } if response.Status != tt.expectedBody.Status { t.Errorf("handler returned unexpected body: got %v want %v", response.Status, tt.expectedBody.Status) } } }) } }