我正在尝试为我使用httprouter编写的微服务编写测试。我之前尝试使用这里给出的答案:How to write test with httprouter但这似乎不太相关,因为我在我的微服务中不使用控制器。任何帮助将不胜感激。
这是我到目前为止所拥有的:
package main
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/julienschmidt/httprouter"
)
func TestCreateURL(t *testing.T) {
expected := `{"original_url":"https://www.google.com", "short_url":"https://morning-retreat-24523.herokuapp.com/get/3578"}`
handler := createURL
router := httprouter.New()
router.GET("/new/*url", handler)
req, err := http.NewRequest("GET", "/new/https://www.google.com", nil)
if err != nil {
fmt.Println(err)
}
rr := httptest.NewRecorder()
router.ServeHTTP(rr, req)
if rr.Body.String() != expected {
t.Errorf("Handler returned unexpected body: Got %v but want %v",
rr.Body.String(), expected)
}
}
createURL是这样的函数(但显然还有很多):
func createURL(res http.ResponseWriter, req *http.Request, ps httprouter.Params) {
}