httptest.go 779 B

1234567891011121314151617181920212223242526272829303132333435
  1. //go:build unit
  2. package testutil
  3. import (
  4. "io"
  5. "net/http"
  6. "net/http/httptest"
  7. "strings"
  8. "github.com/gin-gonic/gin"
  9. )
  10. func init() {
  11. gin.SetMode(gin.TestMode)
  12. }
  13. // NewGinTestContext 创建一个 Gin 测试上下文和 ResponseRecorder。
  14. // body 为空字符串时创建无 body 的请求。
  15. func NewGinTestContext(method, path, body string) (*gin.Context, *httptest.ResponseRecorder) {
  16. rec := httptest.NewRecorder()
  17. c, _ := gin.CreateTestContext(rec)
  18. var bodyReader io.Reader
  19. if body != "" {
  20. bodyReader = strings.NewReader(body)
  21. }
  22. c.Request = httptest.NewRequest(method, path, bodyReader)
  23. if method == http.MethodPost || method == http.MethodPut || method == http.MethodPatch {
  24. c.Request.Header.Set("Content-Type", "application/json")
  25. }
  26. return c, rec
  27. }