gin 기반 유닛 테스트 httptest

7705 단어 유닛 테스트
현재 우리 의 백 엔 드 서 비 스 는 대량의 restful api 인 터 페 이 스 를 제공 하고 있 으 며, 온라인 에 접속 할 때마다 그 인터페이스 가 다시 돌아 와 인력 의 낭 비 를 초래 하 는 것 을 테스트 해 야 한다.마침 이번 단원 테스트 와 지속 적 인 통합 을 빌려 우 리 는 httptest 프레임 워 크 를 도입 하여 gin 과 결합 하여 인터페이스 단원 테스트 를 했다.
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") }) }

완성 하 다.

좋은 웹페이지 즐겨찾기