不扯淡,一个简化后的httptest库

前端之家收集整理的这篇文章主要介绍了不扯淡,一个简化后的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测试功能

原文链接:https://www.f2er.com/go/187758.html

猜你在找的Go相关文章