request, err := http.NewRequest("GET", path, nil)
response := httptest.NewRecorder()
r.ServeHTTP(response, request)
var raw map[string]map[string]string
_ = json.Unmarshal(response.Body.Bytes(), &raw)
details := raw["response"]
I have a TestFunction in which I am using this code. It is code to test the REST API for a GET request.
In my first test case I hit a defined handler while in the second test case I am hitting some random handler so as to make that case fail.
The code is getting passed but every time the second test case is giving 500 as the response.
Below is the code of my test case.
func TestGetProviders(t *testing.T) {
type args struct {
path string
handler gin.HandlerFunc
}
tests := []struct {
name string
args args
want bool
}{
{
"First",
args{
"/api/v1/providers",
GetProviders,
},
true,
},
{
"Second",
args{
"/demo",
TheFunc,
},
false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
value := copyCodeGet(tt.args.path, tt.args.handler)
if len(value["response"]) > 0 {
statusCode, _ := strconv.Atoi(value["response"]["code"])
if val := statusCode == config.SuccessCode && value["response"]["message"] == config.SuccessMsg; val != tt.want {
t.Errorf("Error is:%v && Status code should be %v, was %d.", value, http.StatusOK, statusCode)
}
}
})
}
}
Finally After Some Discussion with
mkopriva
I Was Able To Solve The Problem.
I have been Using Defer c.Request.Body.Close() in GetErrResponseList inside the
func TheFunc(c *gin.Context) {
GetErrResponseList(c, config.FailureMsg, nil, nil)
}
like this
func GetErrResponseList(c *gin.Context, msg string, data, count interface{}) {
defer c.Request.Body.Close()
response := ResponseControllerList{400, 0, msg, data, count}
c.JSON(200, gin.H{
config.Response: response,
})
}
Which Was Causing The Problem as a request body does not need to be closed in the handler. and so it was closing the body just before it could be used and hence removing it solved the problem.