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

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.