不扯淡,一个简化后的httptest库
发布时间:2020-12-16 09:44:37 所属栏目:大数据 来源:网络整理
导读:先不提本库,给个用 net/http/httptest 库写通用handler测试的方法(来源): package handlersimport ( "net/http" "net/http/httptest" "testing")func TestHealthCheckHandler(t *testing.T) { // Create a request to pass to our handler. We don't have
先不提本库,给个用 package handlers import ( "net/http" "net/http/httptest" "testing" ) func TestHealthCheckHandler(t *testing.T) { // Create a request to pass to our handler. We don't have any query parameters for now,so we'll // pass 'nil' as the third parameter. req,err := http.NewRequest("GET","/health-check",nil) if err != nil { t.Fatal(err) } // We create a ResponseRecorder (which satisfies http.ResponseWriter) to record the response. rr := httptest.NewRecorder() handler := http.HandlerFunc(HealthCheckHandler) // Our handlers satisfy http.Handler,so we can call their ServeHTTP method // directly and pass in our Request and ResponseRecorder. handler.ServeHTTP(rr,req) // Check the status code is what we expect. if status := rr.Code; status != http.StatusOK { t.Errorf("handler returned wrong status code: got %v want %v",status,http.StatusOK) } // Check the response body is what we expect. expected := `{"alive": true}` if rr.Body.String() != expected { t.Errorf("handler returned unexpected body: got %v want %v",rr.Body.String(),expected) } } 很简单,测试一个方法至少要那么多行代码,还只是简单的get请求,至于请求是否加参数,加什么参数,就成了另一个更大的问题。 本库用法//一个永远返回400的测试handler func badHandler(w http.ResponseWriter,r *http.Request) { http.Error(w,"not a regular name or password",http.StatusBadRequest) } //测试这个handler是否返回400 New("/bad",badHandler,t).Do().CheckCode(http.StatusBadRequest) //测试他是不是返回200(当然会测试失败) New("/ok",t).Do().CheckCode(http.StatusOK) //带着header测试 New("/",t).Post().AddParams("name","value1").AddParams("nam22","value3").Do() //带着cookie测试,并且判断结果是否包含字符串。 New("/",cookieHandler,t).Get().AddCookies(cookie).Do().BodyContains("testcookievalue") //获取 *http.ResponseRecorder,然后自己测试 rr = New("/dump",headerHandler,"value1").Do().ResponseRecorder() //给请求加参数,不写默认是GET请求 New("/ok",t).AddParams("a","aa").AddParams("b","bb").Do().CheckCode(http.StatusOK) //http basic auth: New("/bad",t).SetBasicAuth(username,password).Do().CheckCode(http.StatusBadRequest) //自己定制 http.Request: New("/bad",t).SetRequest(req).Do().CheckCode(http.StatusBadRequest) //And more in test file and source code. 必须有 其他库地址:https://github.com/qiuker521/... 后续会增加json测试功能。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |