行业知识
【golang】28、用 httptest 做 web server 的 controller 的单测
2026-11-27 22:52:43
来源:互联网转载
文章目录
- 一、构建 HTTP server
- 1.1 model.go
- 1.2 server.go
- 1.3 curl 验证 server 功能
- 1.3.1 新建
- 1.3.2 查询
- 1.3.3 更新
- 1.3.4 删除
- 二、httptest 测试
- 2.1 完整示例
- 2.2 实现逻辑
- 2.3 其他示例
- 2.4 用 TestMain 避免重复的测试代码
- 2.5 gin ���架的 httptest
一、构建 HTTP server
1.1 model.go
package mainimport ("errors""time")var TopicCache = make([]*Topic, 0, 16)type Topic struct {Id int `json:"id"`Title string `json:"title"`Content string `json:"content"`CreatedAt time.Time `json:"created_at"`}// 从数组中找到一项, 根据 id 找到数组的下标func FindTopic(id int) (*Topic, error) {if err := checkIndex(id); err != nil {return nil, err}return TopicCache[id-1], nil}// 创建一个 Topic 实例, 没有输入参数, 内部根据 Topic 数组的长度来确定新 Topic 的 idfunc (t *Topic) Create() error {// 初始时len 为 0, id 为 1, 即数组下标为0时并不放置元素, 而数组从下标为1才开始放置元素t.Id = len(TopicCache) + 1 // 忽略用户传入的 id, 而是根据数组的长度, 决定此项的 Idt.CreatedAt = time.Now()TopicCache = append(TopicCache, t) // 初始时数组为空, 放入的第一个元素是 Id = 1return nil}// 更新一个 Topic 实例, 通过 id 找到数组下标, 最终改的还是数组里的值func (t *Topic) Update() error {if err := checkIndex(t.Id); err != nil {return err}TopicCache[t.Id-1] = treturn nil}func (t *Topic) Delete() error {if err := checkIndex(t.Id); err != nil {return err}TopicCache[t.Id-1] = nilreturn nil}func checkIndex(id int) error {if id > 0 && len(TopicCache) return errors.New("The topic is not exists!")}return nil}http.HandleFunc("/topic/", handleRequest)http.ListenAndServe(":2017", nil)}// main handler functionfunc handleRequest(w http.ResponseWriter, r *http.Request) {var err errorswitch r.Method {case http.MethodGet:err = handleGet(w, r)case http.MethodPost:err = handlePost(w, r)case http.MethodPut:err = handlePut(w, r)case http.MethodDelete:err = handleDelete(w, r)}if err != nil {http.Error(w, err.Error(), http.StatusInternalServerError)return}}// 获取一个帖子// 如 GET /topic/1func handleGet(w http.ResponseWriter, r *http.Request) error {// 用户输入的 url 中有 id, 通过 path.Base(r.URL.Path) 获取 idid, err := strconv.Atoi(path.Base(r.URL.Path))if err != nil {return err}topic, err := FindTopic(id)if err != nil {return err}// 序列化结果并输出output, err := json.MarshalIndent(&topic, "", "\t\t")if err != nil {return err}w.Header().Set("Content-Type", "application/json")w.Write(output)return nil}// 增加一个帖子// POST /topic/func handlePost(w http.ResponseWriter, r *http.Request) (err error) {// 构造长度为 r.ContentLength 的缓冲区body := make([]byte, r.ContentLength)// 读取到缓冲区r.Body.Read(body)// 反序列化到对象var topic = new(Topic)err = json.Unmarshal(body, &topic)if err != nil {return}// 执行操作err = topic.Create()if err != nil {return}w.WriteHeader(http.StatusOK)return}// 更新一个帖子// PUT /topic/1func handlePut(w http.ResponseWriter, r *http.Request) error {id, err := strconv.Atoi(path.Base(r.URL.Path))if err != nil {return err}topic, err := FindTopic(id)if err != nil {return err}body := make([]byte, r.ContentLength)r.Body.Read(body)json.Unmarshal(body, topic)err = topic.Update()if err != nil {return err}w.WriteHeader(http.StatusOK)return nil}// 删除一个帖子// DELETE /topic/1func handleDelete(w http.ResponseWriter, r *http.Request) (err error) {id, err := strconv.Atoi(path.Base(r.URL.Path))if err != nil {return}topic, err := FindTopic(id)if err != nil {return}err = topic.Delete()if err != nil {return}w.WriteHeader(http.StatusOK)return} "id": 1, "title": "a", "content": "b", "created_at": "2024-03-11T10:59:44.043029+08:00"} "id": 1, "title": "c", "content": "d", "created_at": "2024-03-11T10:59:44.043029+08:00"}// mux 是多路复用器的意思mux := http.NewServeMux()mux.HandleFunc("/topic/", handleRequest) // 将 [业务的 handleRequest() 函数] 注册到 mux 的 /topic/ 路由上// 构造一个请求reader := strings.NewReader(`{"title":"e", "content":"f"}`)r, _ := http.NewRequest(http.MethodPost, "/topic/", reader)// 构造一个响应 (httptest.ResponseRecorder 实现了 http.ResponseWriter 接口)w := httptest.NewRecorder()mux.ServeHTTP(w, r)//handleRequest(w, r)// 获取响应结果resp := w.Result()if resp.StatusCode != http.StatusOK {t.Errorf("Expected status OK; got %v", resp.Status)}}mux := http.NewServeMux()mux.HandleFunc("/topic/", handleRequest)r, _ := http.NewRequest(http.MethodGet, "/topic/1", nil)w := httptest.NewRecorder()mux.ServeHTTP(w, r)resp := w.Result()if resp.StatusCode != http.StatusOK {t.Errorf("Expected status OK; got %v", resp.Status)}topic := new(Topic)json.Unmarshal(w.Body.Bytes(), topic)if topic.Id != 1 {t.Errorf("cannot get topic by id")}}w = httptest.NewRecorder()os.Exit(m.Run())}ID uint64 `json:"id"`Name string `json:"name"`}func handler(c *gin.Context) {var info userINfoif err := c.ShouldBindJSON(&info); err != nil {log.Panic(err)}fmt.Println(info)c.Writer.Write([]byte(`{"status": 200}`))}func TestHandler(t *testing.T) {rPath := "/user"router := gin.Default()router.GET(rPath, handler)req, _ := http.NewRequest("GET", rPath, strings.NewReader(`{"id": "1","name": "joe"}`))w := httptest.NewRecorder()router.ServeHTTP(w, req)t.Logf("status: %d", w.Code)t.Logf("response: %s", w.Body.String())}
上一篇:水量服务器水管怎么走?