在 Test
中在模拟接口测试,首先我们先实现一个最基础的 Test
例子:
模拟一个 ping/pong
的最基本请求,我们先写一个返回 pong
的HTTP 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())
}
}