先不提本库,给个用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 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的测试handlerfunc badHandler(w http.ResponseWriter,r *http.Request) { http.Error(w,"not a regular name or password",http.StatusBadRequest)}//测试这个handler是否返回400New("/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.
必须有 .Do()
,才能进行请求,不然不会请求。
Check *** 作要在.Do()
后,初始化 *** 作要在.Do()
之前。
库地址:https://github.com/qiuker521/...
后续会增加Json测试功能。
总结以上是内存溢出为你收集整理的不扯淡,一个简化后的httptest库全部内容,希望文章能够帮你解决不扯淡,一个简化后的httptest库所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)