如何编写具有c * gin.Context参数的函数的测试用例

时间:2018-09-11 10:56:44

标签: unit-testing go table-driven

我正在用golang为我的项目编写控制器的测试用例。在控制器中,函数名称SaveProvider()具有参数c *gin.Context,但我不知道如何将JSON传递给c *gin.Context这个参数,以及如何测试控制器中使用的函数谁能告诉我这段代码是怎么回事。它也称为表驱动测试。

package controllers

import (
    "bkapiv1/models"
    "fmt"
    "testing"

    "github.com/gin-gonic/gin"
)

func TestSaveProvider(t *testing.T) {
    type args struct {
        c    *gin.Context
        json ProviderProfile
    }
    tests := []struct {
        name string
        args args
        want bool
    }{
        {
            "SaveProvider",
            args{
                &gin.Context{
                   //How to pass here a JSON means the below JSON ProviderProfile.
                },
                ProviderProfile{
                     models.User{
                         FirstName:                  "Harry",
                         LastName:                   "Potter",
                         FullName:                   "Harry Potter",
                         CompanyName:                "TheIronNetwork",
                         EmailId:                   "harry@gmail.com",
                         Password:                   "vadhera123",
                     },
                     models.AddressStruct{},
                     models.Provider{
                        ProviderCategory: "IC",
                        Priority:         1,
                     },
                },
            },
            true,
         },
     }
     for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            SaveProvider(tt.args.c)
        })
     }
}

控制器中的功能是:-

func SaveProvider(c *gin.Context){

}

1 个答案:

答案 0 :(得分:1)

您想做的事有library

handler := func(w http.ResponseWriter, r *http.Request) {
    c := CreateTestContext(w)
    SaveProvider(c)
}

req := httptest.NewRequest("GET", "http://example.com/foo", nil)
w := httptest.NewRecorder()
handler(w, req)

resp := w.Result()
body, _ := ioutil.ReadAll(resp.Body)

fmt.Println(resp.StatusCode)
fmt.Println(resp.Header.Get("Content-Type"))
fmt.Println(string(body))