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) {
// 创建一个新的HTTP服务器,用于处理请求
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, World!")
})
server := &http.Server{Addr: ":8080", Handler: mux}
// 启动HTTP服务器
go func() {
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
t.Errorf("Error starting server: %v", err)
}
}()
// 等待服务器启动 "github.com/gin-gonic/gin"
time.Sleep(1 * time.Second) "github.com/stretchr/testify/assert"
"gorm.io/gorm"
)
// 创建一个HTTP客户端 func TestUserController_Register(t *testing.T) {
client := &http.Client{ testCases := []struct {
Timeout: 5 * time.Second, desc string
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"),
},
} }
// 发送一个GET请求到服务器 for _, tC := range testCases {
resp, err := client.Get("http://localhost:8080") t.Run(tC.desc, func(t *testing.T) {
if err != nil { gin.SetMode(gin.TestMode)
t.Errorf("Error sending request: %v", err) r := gin.New()
return r.Use(func(c *gin.Context) {
} c.Set(controller.USER_ID_KEY, uint(1))
defer resp.Body.Close() })
// 发送一个POST请求到服务器 ctrl := &controller.UserController{
resp, err = client.Post("http://localhost:8080", "application/json", nil) db: &gorm.DB{},
if err != nil { }
t.Errorf("Error sending request: %v", err) _ = model.Migrate(ctrl.db)
return ctrl.db = model.MockDB()
}
defer resp.Body.Close()
// 检查响应是否成功 var resp *httptest.ResponseRecorder
if resp.StatusCode != http.StatusOK { if data, err := tC.req.ToJSON(); err != nil {
t.Errorf("Unexpected status code: %d", resp.StatusCode) t.Fatalf("failed to marshal request to JSON: %v", err)
return } else {
} req, _ := http.NewRequest(http.MethodPost, "/register", strings.NewReader(data))
// 读取响应内容 resp = httptest.NewRecorder()
body, err := io.ReadAll(resp.Body) r.POST("/register", func(c *gin.Context) {
if err != nil { if err := ctrl.Register(c, tC.req); err != nil {
t.Errorf("Error reading response body: %v", err) c.AbortWithStatus(http.StatusInternalServerError)
return }
} c.AbortWithStatus(http.StatusOK)
})
r.ServeHTTP(resp, req)
}
// 检查响应内容是否正确 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