How to write the test case of When a function having the parameters of c *gin.Context

3.3k Views Asked by At

I'm writing the test cases of the controllers for my project in golang. In the controllers there is the function name SaveProvider()having parameter c *gin.Context and I don't know how to pass the JSON to the c *gin.Context this parameter and How I test my functions used in the controllers Can anyone tell me that How What is the problem in this code.It is also called table driven test.

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:                   "[email protected]",
                         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)
        })
     }
}

The function in the controller is:-

func SaveProvider(c *gin.Context){

}
1

There are 1 best solutions below

1
On

there is a library for what you want to do

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