Commit 75c47933 authored by 李宇怀's avatar 李宇怀
Browse files

更新了一版模板

parent 2e8eb26f
package main package main
import ( import (
"fmt" "errors"
"io" "go-svc-tpl/api/dto"
"go-svc-tpl/internal/controller"
"go-svc-tpl/internal/dao/model"
"net/http" "net/http"
"net/http/httptest"
"strings"
"testing" "testing"
"time"
)
func TestMyController(t *testing.T) { "github.com/gin-gonic/gin"
// 创建一个新的HTTP服务器,用于处理请求 "github.com/stretchr/testify/assert"
mux := http.NewServeMux() "gorm.io/gorm"
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { )
fmt.Fprintf(w, "Hello, World!")
})
server := &http.Server{Addr: ":8080", Handler: mux}
// 启动HTTP服务器 func TestUserController_Register(t *testing.T) {
go func() { testCases := []struct {
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed { desc string
t.Errorf("Error starting server: %v", err) req *dto.UserRegisterReq
expected error
}{
{
desc: "success",
req: &dto.UserRegisterReq{
Email: "test@test.com",
Password: "password",
Name: "test",
},
expected: nil,
},
{
desc: "invalid email",
req: &dto.UserRegisterReq{
Email: "test@test",
Password: "password",
Name: "test",
},
expected: errors.New("wrong email pattern"),
},
} }
}()
// 等待服务器启动 for _, tC := range testCases {
time.Sleep(1 * time.Second) t.Run(tC.desc, func(t *testing.T) {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(func(c *gin.Context) {
c.Set(controller.USER_ID_KEY, uint(1))
})
// 创建一个HTTP客户端 ctrl := &controller.UserController{
client := &http.Client{ db: &gorm.DB{},
Timeout: 5 * time.Second,
} }
_ = model.Migrate(ctrl.db)
ctrl.db = model.MockDB()
// 发送一个GET请求到服务器 var resp *httptest.ResponseRecorder
resp, err := client.Get("http://localhost:8080") if data, err := tC.req.ToJSON(); err != nil {
if err != nil { t.Fatalf("failed to marshal request to JSON: %v", err)
t.Errorf("Error sending request: %v", err) } else {
return req, _ := http.NewRequest(http.MethodPost, "/register", strings.NewReader(data))
}
defer resp.Body.Close()
// 发送一个POST请求到服务器 resp = httptest.NewRecorder()
resp, err = client.Post("http://localhost:8080", "application/json", nil) r.POST("/register", func(c *gin.Context) {
if err != nil { if err := ctrl.Register(c, tC.req); err != nil {
t.Errorf("Error sending request: %v", err) c.AbortWithStatus(http.StatusInternalServerError)
return
} }
defer resp.Body.Close() c.AbortWithStatus(http.StatusOK)
})
// 检查响应是否成功 r.ServeHTTP(resp, req)
if resp.StatusCode != http.StatusOK {
t.Errorf("Unexpected status code: %d", resp.StatusCode)
return
}
// 读取响应内容
body, err := io.ReadAll(resp.Body)
if err != nil {
t.Errorf("Error reading response body: %v", err)
return
} }
// 检查响应内容是否正确 assert.Equal(t, http.StatusOK, resp.Code)
expected := "Hello, World!" assert.Equal(t, tC.expected, nil)
if string(body) != expected { })
t.Errorf("Unexpected response body: %s", string(body))
return
} }
// 关闭HTTP服务器
server.Close()
} }
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment