Code2-使用httptest模拟接口测试

21次阅读

共计 596 个字符,预计需要花费 2 分钟才能阅读完成。

Test 中在模拟接口测试,首先我们先实现一个最基础的 Test 例子:

模拟一个 ping/pong 的最基本请求,我们先写一个返回 pongHTTP handler

import (
    "io"
    "net/http"
    "net/http/httptest"
    "testing"
)

func Pong(w http.ResponseWriter, r *http.Request) {w.WriteHeader(http.StatusOK)
    w.Header().Set("Content-Type", "text/plain")
    io.WriteString(w, "pong")
}

然后写测试用例:

func TestRequest(t *testing.T) {req, err := http.NewRequest("GET", "ping", nil)
    if err != nil {t.Fatal(err)
    }

    rr := httptest.NewRecorder()
    handler := http.HandlerFunc(Pong)

    handler.ServeHTTP(rr, req)

    if status := rr.Code; status != http.StatusOK {t.Errorf("status code %v", rr.Code)
    }

    if rr.Body.String() != "pong" {t.Errorf("returned %s", rr.Body.String())
    }
}

正文完
 0