不扯淡,一個簡化後的httptest庫

大舒發表於2019-02-16

先不提本庫,給個用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測試功能。

相關文章