如何在Golang中测试http请求处理程序?

Ser*_*rov 5 testing http go

我有一组请求处理程序,如下所示:

func GetProductsHandler(w http.ResponseWriter, req *http.Request) {
    defer req.Body.Close()
    products := db.GetProducts()

    //    ...
    // return products as JSON array
}
Run Code Online (Sandbox Code Playgroud)

我该如何以正确的方式测试它们?我应该将模拟ResponseWriter和Request对象发送到该函数并查看结果吗?

是否有工具在Go中模拟请求和响应对象以简化过程而无需在测试之前启动服务器?

dm0*_*514 8

Go提供了一个模拟编写器,用于测试处理程序.的标准库的文档提供了一个例子:

package main

import (
    "fmt"
    "net/http"
    "net/http/httptest"
)

func main() {
    handler := func(w http.ResponseWriter, r *http.Request) {
        http.Error(w, "something failed", http.StatusInternalServerError)
    }

    req := httptest.NewRequest("GET", "http://example.com/foo", nil)
    w := httptest.NewRecorder()
    handler(w, req)

    fmt.Printf("%d - %s", w.Code, w.Body.String())
}
Run Code Online (Sandbox Code Playgroud)

我认为拥有一个全局依赖(db)会对完整的单元测试产生影响.使用go你的测试可以重新分配一个值,掩盖,全局值db.

另一个策略(我的首选)是将处理程序打包在一个结构中,该结构具有一个db属性.

type Handlers struct {
  db DB_INTERFACE
}

func (hs *Handlers) GetProductsHandler(w http.ResponseWriter, req *http.Request) {...}
Run Code Online (Sandbox Code Playgroud)

这样,您的测试可以Handlers使用存根db对象实例化,这将允许您创建无IO单元测试.