如何为基于 net/http 的代码编写集成测试?
How to write integration tests for net/http based 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)
}
这是我写的测试用例:
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())
}
}
这个测试真的是通过TCP套接字发送一个HTTP请求并到达终点/
吗?或者这只是在不建立 HTTP 连接的情况下调用函数?
更新
根据@ffk的回答,我写了这样的测试:
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))
}
}
如果要实例化可通过 127.0.0.1 上的随机 tcp 端口访问的测试服务器,请使用以下命令:
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)
有关详细信息,请参阅 https://golang.org/pkg/net/http/httptest/#NewServer
这是一个示例代码:
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)
}
这是我写的测试用例:
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())
}
}
这个测试真的是通过TCP套接字发送一个HTTP请求并到达终点/
吗?或者这只是在不建立 HTTP 连接的情况下调用函数?
更新
根据@ffk的回答,我写了这样的测试:
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))
}
}
如果要实例化可通过 127.0.0.1 上的随机 tcp 端口访问的测试服务器,请使用以下命令:
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)
有关详细信息,请参阅 https://golang.org/pkg/net/http/httptest/#NewServer