Go   发布时间:2022-04-09  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了不扯淡,一个简化后的httptest库大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

先不提本库,给个用net/http/httptest库写通用handler测试的方法(来源):

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.

必须有 .Do(),才能进行请求,不然不会请求。
Check操作要在.Do()后,初始化操作要在.Do()之前。

其他

库地址:https://github.com/qiuker521/...

后续会增加json测试功能

大佬总结

以上是大佬教程为你收集整理的不扯淡,一个简化后的httptest库全部内容,希望文章能够帮你解决不扯淡,一个简化后的httptest库所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: