不扯淡,一个简化后的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", badHandler, t).Do().CheckCode(http.StatusOK)

//带着header测试
New("/", badHandler, 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, t).Post().AddParams("name", "value1").Do().ResponseRecorder()

//给请求加参数,不写默认是GET请求
New("/ok", badHandler, t).AddParams("a", "aa").AddParams("b", "bb").Do().CheckCode(http.StatusOK)

//http basic auth:
New("/bad", badHandler, t).SetBasicAuth(username, password).Do().CheckCode(http.StatusBadRequest)

//自己定制 http.Request:
New("/bad", badHandler, 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://segmentfault.com/a/1190000011844811
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞