Files

50 lines
1.2 KiB
Go

package middleware
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
)
// newTestRouter 构建仅含健康检查路由的测试引擎。
func newTestRouter() *gin.Engine {
gin.SetMode(gin.TestMode)
r := gin.New()
HealthRegister(r)
return r
}
// TestHealthHandler_StatusOK 验证 GET /health 返回 200 与 {"status":"ok"}。
func TestHealthHandler_StatusOK(t *testing.T) {
r := newTestRouter()
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/health", nil)
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("HTTP 状态码 = %d, 期望 200", w.Code)
}
if got := w.Body.String(); got != `{"status":"ok"}` {
t.Errorf("响应体 = %s, 期望 {\"status\":\"ok\"}", got)
}
if ct := w.Header().Get("Content-Type"); ct != "application/json; charset=utf-8" {
t.Errorf("Content-Type = %q, 期望 application/json", ct)
}
}
// TestHealthHandler_MethodNotAllowed 验证非 GET 请求返回 404。
func TestHealthHandler_MethodNotAllowed(t *testing.T) {
r := newTestRouter()
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/health", nil)
r.ServeHTTP(w, req)
if w.Code != http.StatusNotFound {
t.Errorf("POST /health 状态码 = %d, 期望 404", w.Code)
}
}