在对http服务测试时,我们可以通过两种方式来完成,一种基于http服务,一种基于自带的测试包来完成。
func TestHelloHandleFunc(t *testing.T) { rw := httptest.NewRecorder() req := httptest.NewRequest(http.MethodPost, "/hello, nil) handleHello(rw, req) if rw.Code != http.StatusOK { t.Errorf("status code not ok, status code is %v", rw.Code) } }
go test -run=TestHTTPServer
func TestHTTPServer(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(handleHello)) defer ts.Close() log.Printf("server url: %s", ts.URL) testURL := ts.URL + "/hello resp, err := http.Get(testURL) if err != nil { t.Error(err) return } if g, w := resp.StatusCode, http.StatusOK; g != w { t.Errorf("status code = %q; want %q", g, w) return } }
go test cover go test -coverprofile=coverage.out go tool cover -html=coverage.out
go test -race
喜欢请关注“云端漫记", 持续为你更新
原创声明,本文系作者授权云+社区发表,未经许可,不得转载。
如有侵权,请联系 yunjia_community@tencent.com 删除。
我来说两句