2

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

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){

}
4

1 回答 1

2

有一个你想做的图书馆

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))
于 2018-09-11T11:39:33.490 回答