douyan1972 2015-05-19 18:00
浏览 38
已采纳

如何为基于net / http的代码编写集成测试?

Here is an example code:

package main

import (
    "net/http"
)

func Home(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Hello, world!"))
}

func Router() *http.ServeMux {
    mux := http.NewServeMux()
    mux.HandleFunc("/", Home)
    return mux
}

func main() {
    mux := Router()
    http.ListenAndServe(":8080", mux)
}

This is the test case I wrote:

package main

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

func TestMain(t *testing.T) {
    w := httptest.NewRecorder()
    r, _ := http.NewRequest("GET", "/", nil)
    Router().ServeHTTP(w, r)
    if w.Body.String() != "Hello, world!" {
        t.Error("Wrong content:", w.Body.String())
    }
}

Is this test really sending an HTTP request through a TCP socket and reaching the end point /? Or this is just calling the function without making an HTTP connection?

Update

Based on the answer given by @ffk I wrote the test like this:

func TestMain(t *testing.T) {
    ts := httptest.NewServer(Router())
    defer ts.Close()
    req, _ := http.NewRequest("GET", ts.URL+"/", nil)
    client := http.Client{}
    resp, _ := client.Do(req)
    defer resp.Body.Close()
    body, _ := ioutil.ReadAll(resp.Body)
    if string(body) != "Hello, world!" {
        t.Error("Wrong content:", string(body))
    }
}
  • 写回答

1条回答 默认 最新

  • douding6266 2015-05-19 20:31
    关注

    If you want to instantiate a test server accessible over a random tcp port on 127.0.0.1, use the following:

    httpHandler := getHttpHandler() // of type http.Handler
    testServer := httptest.NewServer(httpHandler)
    defer testServer.Close()
    request, err := http.NewRequest("GET", testServer.URL+"/my/url", nil)
    client := http.Client{}
    response, err := client.Do(request)
    

    For more info, see https://golang.org/pkg/net/http/httptest/#NewServer

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程