gin 기반 유닛 테스트 httptest
7705 단어 유닛 테스트
httptest 는 golang 이 공식 적 으로 제공 하 는 가방 으로 / src / net / http / http / httptest 아래 에 있 습 니 다.
그 원 리 는 저도 소스 코드 를 보고 연 구 했 습 니 다. 여기 서 대체적으로 ResponseRecorder 구조 체 가 있 습 니 다. http. ResponseWriter 를 실현 하 는 동시에 http. Response 도 포함 되 어 있 습 니 다. 전 자 는 server 엔 드 차원 의 response 이 고 후 자 는 client 엔 드 차원 의 response 입 니 다. 즉, ResponseRecorder 는 server 와 client 의 기능 을 동시에 실현 한 것 입 니 다.
자, 이제 httptest 를 어떻게 사용 하 는 지 보 겠 습 니 다.
httptest 구축
// Get uri, get
func Get(uri string, router *gin.Engine) []byte {
// get
req := httptest.NewRequest("GET", uri, nil)
//
w := httptest.NewRecorder()
// handler
router.ServeHTTP(w, req)
//
result := w.Result()
defer result.Body.Close()
// body
body,_ := ioutil.ReadAll(result.Body)
return body
}
// PostForm uri param, , post
func PostForm(uri string, param url.Values, router *gin.Engine) []byte {
// post
req := httptest.NewRequest("POST", uri, strings.NewReader(param.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
//
w := httptest.NewRecorder()
// handler
router.ServeHTTP(w, req)
//
result := w.Result()
defer result.Body.Close()
// body
body, _ := ioutil.ReadAll(result.Body)
return body
}
gin 에 루트 를 등록 하고 인터페이스 샘플 두 개 를 썼 습 니 다.
regAdmin := router.Group("/quote")
regAdmin.GET("/ge", Ge)
regAdmin.POST("/pos", Pos)
type TestForPost struct {
Strname string `form:"strname" binding:"required"`
Number int `form:"number" binding:"required"`
}
// Get
func Ge(c *gin.Context) {
c.String(http.StatusOK, "success")
}
// Post
func Pos(c *gin.Context) {
req := &TestForPost{}
if err := c.ShouldBindWith(req, binding.Form); err != nil {
fmt.Println("bind error",err)
c.JSON(http.StatusOK, gin.H{
"errno":"1",
"errmsg":" ",
"data":"",
})
return
}
c.JSON(http.StatusOK, gin.H{
"errno":"0",
"errmsg":"Null",
"data":req,
})
}
쓰기 단위 테스트
type Response struct {
Errno string `json:"errno"`
Errmsg string `json:"errmsg"`
Data TestForPost `json:"data"`
}
func TestOnGetStringRequest(t *testing.T) {
//
url:="/quote/ge"
// Get
body := Get(url, router)
//
if string(body) != "success" {
t.Errorf(" ,body:%v
",string(body))
}
convey.Convey(" GET ", t, func() {
convey.So(string(body), convey.ShouldEqual, "success")
})
}
func TestOnPostRequestForForm(t *testing.T) {
//
uri := "/quote/pos"
param := url.Values{
"strname":{"test"},
"number":{"1"},
}
// post ,
body := PostForm2(uri, param, router)
//body := PostForm3(uri, param, router)
// ,
response := &Response{}
if err := json.Unmarshal(body, response); err != nil {
t.Errorf(" ,err:%v
",err)
}
t.Log(response.Data)
if response.Data.Strname != "test" {
t.Errorf(" ,errmsg:%v, data:%v
",response.Errmsg,response.Data.Strname)
}
convey.Convey(" POST ", t, func() {
convey.So(response.Data.Strname, convey.ShouldEqual, "test")
})
}
완성 하 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
자바 에서 sax 분석 xmlSax 해석 은 xml 파일 의 순서에 따라 해석 되 기 때문에 을 읽 을 때 startDocument () 방법 을 호출 합 니 다. 주의: 환경 이 다 르 기 때문에 두 번 째 매개 변 수 는 비어 있 을 수도 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.